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


在本节中,我们来看一下 C++ 中的 RTTI(运行时类型信息)。在 C++ 中,RTTI 是一种机制,它可以在运行时显示有关对象数据类型的信息。此功能仅当类至少有一个虚拟函数时才可用。它允许在程序执行时确定对象的类型。

在以下示例中,第一个代码将无法运行。它将生成一个错误,例如“无法将 base_ptr(类型为 Base*)动态转换为类型'类 Derived*'(源类型不是多态的)”。出现此错误的原因是此示例中没有虚拟函数。

示例代码

#include<iostream>
using namespace std;
class Base { };
class Derived: public Base {};
int main() {
   Base *base_ptr = new Derived;
   Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);
   if(derived_ptr != NULL)
      cout<<"It is working";
   else
      cout<<"cannot cast Base* to Derived*";
   return 0;
}

现在,在添加了虚拟方法后,它将可以工作。

示例代码

#include<iostream>
using namespace std;
class Base {
   virtual void function() {
      //empty function
   }
};
class Derived: public Base {};
int main() {
   Base *base_ptr = new Derived;
   Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);
   if(derived_ptr != NULL)
      cout<<"It is working";
   else
      cout<<"cannot cast Base* to Derived*";
   return 0;
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

It is working

更新时间: 30-7-2019

520 次浏览

开启您的职业生涯

通过参加课程获得认证

开始操作
广告