C ++程序中的RTTI(运行时类型信息)
在本节中,我们将看到什么是C++中的RTTI(运行时类型信息)。在C++中,RTTI是一种机制,它在运行时公开有关对象数据类型的信息。仅当类具有至少一个虚函数时,此功能才可用。它允许在程序执行时确定对象的类型。
在下面的示例中,第一个代码将不起作用。它将生成一个错误,例如“无法dynamic_castbase_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() {
//空函数
}
};
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