Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tương đương instanceof của Java trong C++


C++ không có từ khóa instanceof như Java. Tuy nhiên, từ C++11 có std::is_base_of<Base, T> để kiểm tra kế thừa tại compile-time, nhưng không kiểm tra đa hình tại runtime.

Cách gần nhất là dùng dynamic_cast<new-type>(expression). Nó chuyển con trỏ cơ sở sang con trỏ dẫn xuất; nếu thất bại trả về nullptr. Yêu cầu: class phải đa hình (có hàm ảo) và bật RTTI.

Ví dụ triển khai instanceof

#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() { cout << "Parent\n"; }
};

class Child : public Parent {
public:
    virtual void foo() { 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 là Parent\n";
    if (instanceof<Parent>(ptr2)) cout << "c là Parent\n";
    if (instanceof<Child>(ptr2))  cout << "c là Child\n";
    if (instanceof<Child>(ptr1))  cout << "p KHÔNG phải Child\n";
    if (instanceof<AnotherClass>(ptr2)) cout << "c KHÔNG phải AnotherClass\n";
}

Kết quả

p là Parent
c là Parent
c là Child
p KHÔNG phải Child
c KHÔNG phải AnotherClass