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
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短