📜  C++ 中的 RTTI(运行时类型信息)

📅  最后修改于: 2022-05-13 01:55:29.137000             🧑  作者: Mango

C++ 中的 RTTI(运行时类型信息)

在 C++ 中,RTTI(运行时类型信息)是一种在运行时公开有关对象数据类型的信息的机制,并且仅适用于具有至少一个虚函数的类。它允许在程序执行期间确定对象的类型。

运行时强制转换

运行时强制转换检查强制转换是否有效,是使用指针或引用确定对象的运行时类型的最简单方法。当我们需要将指针从基类转换为派生类型时,这尤其有用。在处理类的继承层次结构时,通常需要对对象进行强制转换。有两种类型的铸造:

  1. Upcasting:当派生类对象的指针或引用被视为基类指针时。
  2. 向下转换:当基类指针或引用转换为派生类指针时。

使用 dynamic_cast:在继承层次结构中,它用于将基类指针向下转换为子类。成功转换时,它返回转换后类型的指针,但是,如果我们尝试转换无效类型(例如不是所需子类类型的对象指针),它就会失败。

例如,dynamic_cast 使用 RTTI,以下程序失败,并出现错误“cannot dynamic_cast `b' (of type `class B*') to type `class D*' (source type is not polymorphic)”,因为没有虚函数在基类 B 中。

CPP
// CPP program to illustrate
// Run Time Type Identification
#include 
using namespace std;
class B {
};
class D : public B {
};
  
// Driver Code
int main()
{
    B* b = new D;
    D* d = dynamic_cast(b);
    if (d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar();
    return 0;
}


CPP
// CPP program to illustrate
// Run Time Type Identification
#include 
using namespace std;
class B {
    virtual void fun() {}
};
class D : public B {
};
  
// Driver Code
int main()
{
    B* b = new D;
    D* d = dynamic_cast(b);
    if (d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar();
    return 0;
}


向基类 B 添加一个虚函数使其工作。

CPP

// CPP program to illustrate
// Run Time Type Identification
#include 
using namespace std;
class B {
    virtual void fun() {}
};
class D : public B {
};
  
// Driver Code
int main()
{
    B* b = new D;
    D* d = dynamic_cast(b);
    if (d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar();
    return 0;
}
输出
works