使用运行是类型标识来确定对象的类型

 使用运行是类型标识(RTTI)来确定对象的类型。typeid通过查询一个对象的地址以得到这个地址指向的对象的类型。下面给出简单的例子:

 

 

 

 

#include <iostream>
#include <typeinfo>
using namespace std;
class Base{};
class Drived:public Base {};
int main()
{
 Base b,bb;
 Drived d;
 if(typeid(b)==typeid(bb))
 {
  cout<<"b and bb are the same type"<<endl;
 }
 else
 {
  cout<<"b and bb are not the same type"<<endl;
 }
 if(typeid(b)==typeid(d))
 {
  cout<<"b and d are the same type"<<endl;
 }
 else
 {
  cout<<"b and d are not the same type"<<endl;
 }
 cout<<typeid(d).name()<<endl;
}

 

  typeid返回一个指向一个静态对象的引用,如果在两个相同类型的对象上调用的话旧得到指向同一个对象的索引,这样就能确这他们是同一个类型。使用typeid().name()可以返回类的名称。

  RTTI是会增加系统开销的。默认情况编译器没有打开。其实这种方式也不是唯一获得类型信息的方法,后面的文章我们将讨论另外一种可以得到类型信息的方法。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值