C++运行时获取类型信息的type_info类与bad_typeid异常
type_info 类 class type_info { public: virtual ~type_info(); size_t hash_code() const _CRTIMP_PURE bool operator==(const type_info& rhs) const; _CRTIMP_PURE bool operator!=(const type_info& rhs) const; _CRTIMP_PURE int before(const type_info& rhs) const; _CRTIMP_PURE const char* name() const; _CRTIMP_PURE const char* raw_name() const; }; 您不能直接实例化 type_info 类的对象,因为该类只有一个私有复制构造函数。构造(临时)type_info 对象的唯一方式是使用 typeid 运算符。由于赋值运算符也是私有的,因此不能复制或分配类 type_info 的对象。 bad_typeid 异常 catch (bad_typeid) statement 备注 class bad_typeid : public exception { public: bad_typeid(const char * _Message = "bad typeid"); bad_typeid(const bad_typeid &); virtual ~bad_typeid(); }; 以下示例演示引发 bad_typeid 异常的 typeid 运算符。 // expre_bad_typeid.cpp // compile with: /EHsc /GR #include <typeinfo.h> #include <iostream> class A{ public: // object for class needs vtable // for RTTI virtual ~A(); }; using namespace std; int main() { A* a = NULL; try { cout << typeid(*a).name() << endl; // Error condition } catch (bad_typeid){ cout << "Object is NULL" << endl; } } 输出 Object is NULL (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |