相当于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 出阁宴祝福语姐姐简短