Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

C++ Equivalent ของ instanceof ใน Java

C++ ไม่มีวิธีตรวจสอบว่า object เป็น instance ของคลาสหนึ่งโดยตรงเหมือน Java แต่ใน C++11 มี is_base_of<Base, T> เพื่อตรวจสอบว่า Base เป็นคลาสฐานของ T หรือไม่ แต่ไม่ตรวจสอบการใช้งานฟังก์ชัน

วิธีที่ใกล้เคียง instanceof มากที่สุดคือใช้ dynamic_cast<new-type>(expression) ซึ่งพยายามแปลงค่าเป็นชนิดที่ระบุ และคืนค่า null pointer หากล้มเหลว ทำงานได้เฉพาะกับ polymorphic pointers และต้องเปิด RTTI (Run-Time Type Information)

โค้ดตัวอย่าง

#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 Parent" << endl;
    else cout << "p is not an instance of Parent" << endl;

    if (instanceof<Parent>(ptr2)) cout << "c is an instance of Parent" << endl;
    else cout << "c is not an instance of Parent" << endl;

    if (instanceof<Child>(ptr2)) cout << "c is an instance of Child" << endl;
    else cout << "c is not an instance of Child" << endl;

    if (instanceof<Child>(ptr1)) cout << "p is an instance of Child" << endl;
    else cout << "p is not an instance of Child" << endl;

    if (instanceof<AnotherClass>(ptr2)) cout << "c is an instance of AnotherClass" << endl;
    else cout << "c is not an instance of AnotherClass" << 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