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