C++ 程序中的 RTTI(运行时类型信息)
在本文中,我们将学习 C++ 中的 RTTI(运行时类型信息)。在 C++ 中,RTTI 是一个机制,可在运行时公开有关对象的数据类型的信息。仅当类至少有一个虚函数时,此功能才可用。它允许在程序执行时确定对象的类型。
在以下示例中,第一段代码将不起作用。它会生成类似于“无法将 base_ptr(类型为 Base*)动态转换为类型‘class 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