C++中的"instanceof"

       在C++中通过在基类、派生类复写(override)虚函数,基类指针来引用派生类对象,以达到同一个接口表现出不同的行为(即多态)的目的。反过来,我们可能存在这样的需求,仅通过一个基类指针判断它对应的是哪个类的实例。这时应该怎么做?


       在java中,可以通过instanceof(java RTTI的一种方式)运算符,在运行时指出对象是否是特定类的一个实例。而在C++中则可以使用dynamic_cast。

       将一个基类对象指针(或引用)cast到继承类指针,dynamic_cast会根据基类指针是否真正指向继承类指针来做相应处理。对指针进行dynamic_cast,失败返回null,成功返回正常cast后的对象指针;对引用进行dynamic_cast,失败抛出一个异常,成功返回正常cast后的对象引用。


       由于运行时类型检查需要运行时类型信息,而这个信息存储在类的虚函数表中,对没有虚函数的类进行dynamic_cast将会引发编译错误。

#include <iostream>
using namespace std;

class Parent
{
public:
    virtual void display()
    {
        cout << "Parent" << endl;
    }
};

class Son : public Parent
{
public:
    void display()
    {
        cout << "Son" << endl;
    }
};

class Daughter : public Parent
{
public:
    void display()
    {
        cout << "Daughter" << endl;
    }
};

int main()
{
    Parent *p;
    p = new Daughter();

    Daughter* dau = dynamic_cast<Daughter*>(p);
    Son* s = dynamic_cast<Son*>(p);
	
    if(dau != NULL)
    {
        cout << "instanceof Daughter" << endl;
    }
	else if(s != NULL)
    {
        cout << "instanceof Son" << endl;
    }
}


猜你喜欢

转载自blog.csdn.net/i792439187/article/details/69230266