您的位置:首页 > 其它

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

2009-04-22 19:48 288 查看
使用运行是类型标识(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是会增加系统开销的。默认情况编译器没有打开。其实这种方式也不是唯一获得类型信息的方法,后面的文章我们将讨论另外一种可以得到类型信息的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: