1. 程式人生 > 實用技巧 >c++ typeid

c++ typeid

RTTI

在瞭解 typeid 之前,先了解一下 RTTI (Run-Time Type Identification,執行時型別識別 ),它使程式能夠獲取由基指標或引用所指向的物件的實際派生型別,即允許“用指向基類的指標或引用來操作物件”的程式能夠獲取到“這些指標或引用所指物件”的實際派生型別。

typeid

typeid 是 c++ 的關鍵字之一,等同於 sizeof 這類的操作符。typeid 操作符的返回結果是名為 type_info 的標準庫型別的物件的引用(在標頭檔案typeinfo中定義)。

c++ 標準規定了必須實現如下四種運算:

t1 == t2 // 如果兩個物件t1和t2型別相同,則返回true;否則返回false
t1 != t2 // 如果兩個物件t1和t2型別不同,則返回true;否則返回false
t.name() // 返回型別的C-style字串,型別名字用系統相關的方法產生
t1.before(t2) // 指出t1是否出現在t2之前,返回 bool 值

程式中建立type_info物件的唯一方法是使用typeid操作符 。type_info的name成員函式返回C-style的字串,用來表示相應的型別名,但務必注意這個返回的型別名與程式中使用的相應型別名並不一定一致,這具體由編譯器的實現所決定的,標準只要求實現為每個型別返回唯一的字串。

程式碼示例
  #include <iostream>
  using namespace std;
  ​
  class Base {
  public:
      virtual void vvfunc() {}
  };
  ​
  class Derived : public Base {
  };
  ​
  int main()
  {
      Derived* pd = new Derived;
      Base* pb = pd;
  ​
      cout << typeid(pb).name() << endl;  // P4Base
cout << typeid(*pb).name() << endl; // 7Derived cout << typeid(pd).name() << endl; // P7Derived cout << typeid(*pd).name() << endl; // 7Derived delete pd; }