使用关键字 typeid 可以返回 变量/类型 的 类型信息: std::type_info ,该类的定义如下:(经简化)
class type_info {
public:
virtual ~type_info();
bool operator==(const type_info& rhs) const;
bool operator!=(const type_info& rhs) const;
const char* name(__type_info_node* __ptype_info_node = &__type_info_root_node) const;
const char* raw_name() const;
private:
void *_m_data;
char _m_d_name[1];
type_info(const type_info& rhs);
type_info& operator=(const type_info& rhs);
};
== 运算符可以比较两个 对象是否是同一个类型。
name()函数输出该类型的名字。
测试如下:
class CBase
{
public:
CBase()
{
}
virtual ~CBase()
{
}
};
class CDerive : public CBase
{
public:
CDerive(){}
};
int _tmain(int argc, _TCHAR* argv[])
{
CBase base;
CDerive derive;
CBase* p = &base;
CBase* pB = &derive;
CDerive* pD = &derive;
cout<<"typeid(CBase) : "<<typeid(CBase).name()<<endl;
cout<<"typeid(CDerive) : "<<typeid(CDerive).name()<<endl<<endl;
cout<<"typeid(base) : "<<typeid(base).name()<<endl;
cout<<"typeid(derive) : "<<typeid(derive).name()<<endl<<endl;
cout<<"typeid(p) : "<<typeid(p).name()<<endl;
cout<<"typeid(pB) : "<<typeid(pB).name()<<endl;
cout<<"typeid(pD) : "<<typeid(pD).name()<<endl<<endl;
cout<<"typeid(*p) : "<<typeid(*p).name()<<endl;
cout<<"typeid(*pB) : "<<typeid(*pB).name()<<endl;
cout<<"typeid(*pD) : "<<typeid(*pD).name()<<endl<<endl;
cout<<endl;
cout<<"typeid(int) : "<<typeid(int).name()<<endl;
cout<<"typeid(float) : "<<typeid(float).name()<<endl;
cout<<"typeid(bool) : "<<typeid(bool).name()<<endl;
cout<<"typeid(double) : "<<typeid(double).name()<<endl;
cout<<"typeid(std::string) : "<<typeid(std::string).name()<<endl;
getchar();
return 0;
}
运行结果:
posted on 2009-06-01 16:13
李阳 阅读(369)
评论(0) 编辑 收藏 引用