typeid 運算子

typeid( type-id )
typeid( expression )

備註

typeid運算子允許在執行階段決定物件型別。

將typeid是 consttype_info 與。  值是參考 type_info 物件,表示其中一個型別 id 或類型的運算式,視何種形式的typeid用。 請參閱 type_info 類別如需詳細資訊。

typeid運算子不適用於 managed 型別 (抽象的多個宣告或執行個體),請參閱typeid如需取得Type指定的型別。

typeid運算子會執行 run-time 檢查,套用至多型類別型別是左值時,則為 true 的型別物件的位置無法由所提供的靜態資訊。 這種情形如下:

  • 類別參考

  • 指標,以解除參考 *

  • 下標的指標 (亦即 [ ]). (請注意它通常是不安全地使用多型型別的指標的註標)。

如果運算式 但物件實際上是衍生自該基底類別,型別指向基底類別型別, type_info 參考衍生的類別為結果。 運算式必須指向多型型別 (具有虛擬函式類別)。 否則,結果就是 type_info 中所參考的靜態類別的運算式。 此外,滑鼠指標必須被解除參考,以便其指向的物件使用。 不需要解除參考指標,結果會是 type_info 所指向的指標,不是哪些 it 點。 例如:

// expre_typeid_Operator.cpp
// compile with: /GR /EHsc
#include <iostream>
#include <typeinfo.h>

class Base {
public:
   virtual void vvfunc() {}
};

class Derived : public Base {};

using namespace std;
int main() {
   Derived* pd = new Derived;
   Base* pb = pd;
   cout << typeid( pb ).name() << endl;   //prints "class Base *"
   cout << typeid( *pb ).name() << endl;   //prints "class Derived"
   cout << typeid( pd ).name() << endl;   //prints "class Derived *"
   cout << typeid( *pd ).name() << endl;   //prints "class Derived"
   delete pd;
}

如果運算式 解除參考指標,而指標的值是零, typeid 就會擲回 bad_typeid 例外狀況。 如果指標不是指向有效的物件, __non_rtti_object例外狀況時,表示嘗試分析觸發錯誤 RTTI (如存取違規),因為物件某種方式不正確 (錯誤的指標或程式碼並不以編譯 /GR)。

如果運算式 就不致於指標或參考基底類別的物件,其結果是 type_info 表示的靜態型別參考運算式靜態型別運算式的參考型別運算式的已知在編譯時期。 評估運算式的靜態型別時,會忽略執行語意。 此外,參照時,會忽略可能在判斷運算式的靜態型別時:

// expre_typeid_Operator_2.cpp
#include <typeinfo>

int main()
{
   typeid(int) == typeid(int&); // evaluates to true
}

typeid 也可用在範本中若要判斷範本參數的型別:

// expre_typeid_Operator_3.cpp
// compile with: /c
#include <typeinfo>
template < typename T > 
T max( T arg1, T arg2 ) {
   cout << typeid( T ).name() << "s compared." << endl;
   return ( arg1 > arg2 ? arg1 : arg2 );
}

請參閱

參考

執行階段型別資訊

C + + 關鍵字