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;
}输出
It is working
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP