在C++中,RTTI(运行时类型信息)是一种在运行时公开有关对象数据类型的信息的机制,并且仅可用于具有至少一个虚函数。它允许在程序执行期间确定对象的类型例如,将dynamic_cast使用RTTI和下面的程序失败,错误“不能将dynamic_cast`B”(类型的`类B *‘)键入`类d *’(源类型不是多态)”,因为没有虚函数在基本类别B。
// CPP program to illustrate
// Run Time Type Identification
#include
using namespace std;
class B { };
class D: public B {};
int main()
{
B *b = new D;
D *d = dynamic_cast(b);
if(d != NULL)
cout<<"works";
else
cout<<"cannot cast B* to D*";
getchar();
return 0;
}
向基类B添加虚拟函数使其可以工作。
// CPP program to illustrate
// Run Time Type Identification
#include
using namespace std;
class B { virtual void fun() {} };
class D: public B { };
int main()
{
B *b = new D;
D *d = dynamic_cast(b);
if(d != NULL)
cout << "works";
else
cout << "cannot cast B* to D*";
getchar();
return 0;
}
输出:
works
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。