RTTI 2011.04.13

本文介绍C++中的RTTI(运行时类型识别)特性,包括typeid操作符和dynamic_cast操作符的使用方法,并通过示例展示了如何确定对象的具体类型及安全地进行类型转换。

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类型的

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值