RTTI(Run-Time Type Identification,通过运行时类型识别)程序能够使用基类的指针或引用来检查这些指针或引用所指的对象的实际派生类型。 RTTI提供了以下两个非常有用的操作符: (1)typeid操作符,返回指针和引用所指的实际类型; (2)dynamic_cast操作符,将基类类型的指针或引用安全地转换为派生类型的指针或引用。
例:
#include <iostream>
using namespace std;
#include <typeinfo>
class A{};
class B : public A{};
class C
{
public:
virtual void f(){}
};
class D : public C{};
int main()
{
const type_info& t1 = typeid(int);
const type_info& t2 = typeid(5);
cout<<t1.name()<<endl;
cout<<(t1 == t2)<<endl;
cout<<(t1 == typeid(5.0))<<endl;
cout<<"---------------------------------------------------------------"<<endl;
A* p1 = new A;
A* p2 = new B;
C* q1 = new C;
C* q2 = new D;
cout<<typeid(*p1).name()<<endl;
cout<<typeid(*p2).name()<<endl;
cout<<typeid(*q1).name()<<endl;
cout<<typeid(*q2).name()<<endl;
cout<<typeid(*q1).before(typeid(*q2))<<endl;
cout<<typeid(*p1).before(typeid(*p2))<<endl;
cout<<"-----------------------------------------------------------------"<<endl;
if (dynamic_cast<D*>(q2) == NULL)
{
cout<<"q2所指对象不是D类型的"<<endl;
}
else
{
cout<<"q2所指对象是D类型的"<<endl;
}
if (dynamic_cast<D*>(q1) == NULL)
{
cout<<"q1所指对象不是D类型的"<<endl;
}
else
{
cout<<"q1所指对象是D类型的"<<endl;
}
delete p1;
delete p2;
delete q1;
delete q2;
return 0;
}
输出:
int
1
0
---------------------------------------------------------------
class A
class A
class C
class D
1
0
-----------------------------------------------------------------
q2所指对象是D类型的
q1所指对象不是D类型的
本文介绍C++中的RTTI(运行时类型识别)特性,包括typeid操作符和dynamic_cast操作符的使用方法,并通过示例展示了如何确定对象的具体类型及安全地进行类型转换。
1135

被折叠的 条评论
为什么被折叠?



