C++ 中 instanceof 的等效物
C++ 没有直接的方法来检查某个对象是否是某个类的某个实例。在 Java 中,我们可以获得这种便利。
在 C++11 中,我们可以找到一个名为 is_base_of<Base, T> 的项。这将检查给定的类是否是给定对象的基类。但是,这不会验证给定的类实例是否使用该函数。
最接近于“instanceof”功能的可能性是使用 dynamic_cast <new-type>(表达式)。这会尝试将给定的值转换为指定类型并返回结果。如果强制转换失败,则返回一个 null 指针。这只适用于多态指针并且在编译器 RTTI 启用时。
示例代码
#include <iostream>
using namespace std;
template<typename Base, typename T>
inline bool instanceof(const T *ptr) {
return dynamic_cast<const Base*>(ptr) != nullptr;
}
class Parent {
public:
virtual ~Parent() {}
virtual void foo () { std::cout << "Parent\n"; }
};
class Child : public Parent {
public:
virtual void foo() { std::cout << "Child\n"; }
};
class AnotherClass{};
int main() {
Parent p;
Child c;
AnotherClass a;
Parent *ptr1 = &p;
Child *ptr2 = &c;
AnotherClass *ptr3 = &a;
if(instanceof<Parent>(ptr1)) {
cout << "p is an instance of the class Parent" << endl;
} else {
cout << "p is not an instance of the class Parent" << endl;
}
if(instanceof<Parent>(ptr2)) {
cout << "c is an instance of the class Parent" << endl;
} else {
cout << "c is not an instance of the class Parent" << endl;
}
if(instanceof<Child>(ptr2)) {
cout << "c is an instance of the class Child" << endl;
} else {
cout << "c is not an instance of the class Child" << endl;
}
if(instanceof<Child>(ptr1)) {
cout << "p is an instance of the class Child" << endl;
} else {
cout << "p is not an instance of the class Child" << endl;
}
if(instanceof<AnotherClass>(ptr2)) {
cout << "c is an instance of AnotherClass class" << endl;
} else {
cout << "c is not an instance of AnotherClass class" << endl;
}
}输出
p is an instance of the class Parent c is an instance of the class Parent c is an instance of the class Child p is not an instance of the class Child c is not an instance of AnotherClass class
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP