相当于instanceof的C ++
C++没有直接方法来检查一个对象是否是某些类类型的实例。在Java中,我们可以获得这种便利。
在C++11中,我们可以找到一个名为is_base_of<Base,T>的项目。这将检查给定的类是否为给定对象的基础。在这里,我们将像javainstanceof一样更改其样式。让我们看看代码。
范例程式码
#include <iostream>
using namespace std;
template<typename Base, typename T>
inline bool instanceof(const T*) {
return is_base_of<Base, T>::value;
}
class Parent{ };
class Child : Parent { };
class AnotherClass{};
int main() {
Child *c;
if(instanceof<Child>(c)) {
cout << "c is instance of Child class" << endl;
} else {
cout << "c is not instance of Child class" << endl;
}
if(instanceof<Parent>(c)) {
cout << "c is instance of Parent class" << endl;
} else {
cout << "c is not instance of Parent class" << endl;
}
if(instanceof<AnotherClass>(c)) {
cout << "c is instance of AnotherClass class" << endl;
} else {
cout << "c is not instance of AnotherClass class" << endl;
}
}输出结果
c is instance of Child class c is instance of Parent class c is not instance of AnotherClass class
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语