複製鏈接
請複製以下鏈接發送給好友

typeid

(c++中使用)

鎖定
在c++中,typeid用於返回指針或引用所指對象的實際類型。
中文名
typeid
作    用
獲知一個變量的具體類型
注    意
typeid是操作符
性    質
g++中
C++的typeid
注意:typeid是操作符,不是函數!
運行時獲知變量類型名稱,可以使用 typeid(變量).name(),需要注意不是所有編譯器都輸出"int"、"float"等之類的名稱,對於這類的編譯器可以這樣使用:float f = 1.1f; if〖 typeid(f)== typeid(0.0f) 〗……
補充:對非引用類型,typeid是在編譯時期識別的,只有引用類型才會在運行時識別。
示例代碼:
#include <iostream>
#include <typeinfo>
using namespace std;
int main(void)
{
    // sample 1 
    cout << typeid(1.1f).name() << endl;  
    // sample 2 
    class Base1 {}; 
    class Derive1:public Base1 {}; 
    Derive1 d1; 
    Base1& b1 = d1; 
    cout << typeid(b1).name() << endl; // 輸出"class Base1",因為Derive1和Base1之間沒有多態性 
    // sample 3, 編譯時需要加參數 /GR 
    class Base2 {  
        virtual void fun( void ) {} 
    }; 
    class Derive2:public Base2 { }; 
    Derive2 d2; 
    Base2& b2 = d2; 
    cout << typeid(b2).name() << endl; // 輸出"class Derive2",因為Derive1和Base1之間有了多態性 
    // sample 4 
    class Derive22:public Base2 { }; // 指針強制轉化失敗後可以比較指針是否為零,而引用卻沒辦法,所以引用制轉化失敗後拋出異常 
    Derive2* pb1 = dynamic_cast<Derive2*>(&b2); 
    cout << boolalpha << (0!=pb1) << endl; // 輸出"true",因為b2本身確實是指向Derive2 
    Derive22* pb2 = dynamic_cast<Derive22*>(&b2);
    cout << boolalpha << (0!=pb2) << endl; // 輸出"false",因為b2本身不是指向Derive22 
    try {  
        Derive2& rb1 = dynamic_cast<Derive2&>(b2);  
        cout << "true" << endl; 
    }catch( bad_cast ) { 
    cout << "false" << endl; } 
    try{  Derive22& rb2 = dynamic_cast<Derive22&>(b2);  cout << "true" << endl; } catch( ... ) // 應該是 bad_cast,但不知道為什麼在VC++6.0中卻不行?因為VC++6.0默認狀態是禁用 RTTI 的,啓用方式:project->setting->c/c++->category->c++ Language 下面第二個複選框選中。 
    {  cout << "false" << endl; } return 0;}