type_info 類
type_info 類描述編譯器在程序中生成的類型信息。此類的對(duì)象可以有效存儲(chǔ)指向類型的名稱的指針。 type_info 類還可存儲(chǔ)適合比較兩個(gè)類型是否相等或比較其排列順序的編碼值。類型的編碼規(guī)則和排列順序是未指定的,并且可能因程序而異。
必須包含 <typeinfo> 標(biāo)頭文件才能使用 type_info 類。 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;};
您不能直接實(shí)例化 type_info 類的對(duì)象,因?yàn)樵擃愔挥幸粋€(gè)私有復(fù)制構(gòu)造函數(shù)。構(gòu)造(臨時(shí))type_info 對(duì)象的唯一方式是使用 typeid 運(yùn)算符。由于賦值運(yùn)算符也是私有的,因此不能復(fù)制或分配類 type_info 的對(duì)象。
type_info::hash_code 可定義適合將 typeinfo 類型的值映射到索引值的分布的哈希函數(shù)。
運(yùn)算符 == 和 != 分別用于與其他 type_info 對(duì)象比較是否相等和不相等。
類型的排列順序與繼承關(guān)系之間沒有關(guān)聯(lián)。使用 type_info::before 成員函數(shù)可確定類型的排序順序。不能保證 type_info::before 在不同的程序中(甚至是多次運(yùn)行同一程序時(shí))會(huì)產(chǎn)生相同的結(jié)果。這樣,type_info::before 類似于 address-of (&) 運(yùn)算符。
type_info::name 成員函數(shù)可將 const char* 返回到以 null 結(jié)尾的字符串,該字符串表示類型的用戶可讀名稱。將緩存所指向的內(nèi)存,應(yīng)該從不直接釋放它。
type_info::raw_name 成員函數(shù)可將 const char* 返回到以 null 結(jié)尾的字符串,該字符串表示對(duì)象類型的修飾名稱。該名稱實(shí)際上以其修飾的形式存儲(chǔ)以節(jié)省空間。因此,此函數(shù)比 type_info::name 更快,因?yàn)樗恍枰∠揎椕Q。 type_info::raw_name 函數(shù)返回的字符串在比較運(yùn)算符中很有用,但它不可讀。如果您需要用戶可讀的字符串,請(qǐng)改用 type_info::name 函數(shù)。
bad_typeid 異常
當(dāng) typeid 的操作數(shù)是 Null 指針時(shí),typeid 運(yùn)算符將引發(fā) bad_typeid 異常。
語法
catch (bad_typeid)statement
備注
bad_typeid 的接口為:
class bad_typeid : public exception{public: bad_typeid(const char * _Message = "bad typeid"); bad_typeid(const bad_typeid &); virtual ~bad_typeid();};
以下示例演示引發(fā) bad_typeid 異常的 typeid 運(yùn)算符。
// 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