執行時型別識別rtti(即run-time type identification).
主要通過typeid和dynamic_cast來實現
typeid操作符
type_info實現如下:
class type_info
應用如下:
typeid
(* obj)
.name()
;//列印出指標obj指向的實際的物件型別if(
typeid
(* obj)
==typeid
(bird));
//判斷obj是否是bird型別
也可以判斷普通的資料型別:
int i=0;
std:
:cout<<
typeid
(i).
name()
<:endl;
dynamic_cast
如下:
bird *bird=dynamic_cast>
(obj)
;//將obj轉換為bird型別的指標(注意:<>內寫要轉換的目標型別)
下面展示展示乙個例項:
//rtti執行時型別識別
#include
#include
using namespace std;
class flyable
;class plane :public flyable
virtual void
land()
void
carry()
};class bird :public flyable
virtual void
land()
void
birdcall()
};//定義乙個全域性函式
void
dosomething
(flyable *obj)if(
typeid
(*obj)
==typeid
(plane)
) obj->
land()
;}intmain
(void
)
執行時型別識別(RTTI)
執行時型別識別 rtti 即是程式執行過程中知道某個物件屬於某個類,我們平時用c 程式設計接觸的rtti一般是編譯器的rtti,即是在新版本的vc 編譯器裡面選用 使能rtti 然後載入typeinfo.h檔案,就可以使用乙個叫typeid 的運運算元,它的地位與在c 程式設計中的sizeof 運運...
RTTI 執行時型別識別
執行時型別識別也是面試時常問的問題,今天整理一下,作為學習和分享 在存在虛函式表的繼承關係時,每個虛函式表前面都設定有乙個type info指標,用於支援rtti,rtti是為多型而生成的資訊,包括物件繼承關係,物件本身的描述等,只有具有虛函式的物件才會生成。執行時型別識別 run time typ...
C 11 執行時型別識別(RTTI)
c 11裡的rtti更好用了,參見這裡 與rtti相關的有幾個類和方法 type info類在標頭檔案中定義,代表了乙個c 型別的相關資訊。一般由typeid操作符返回,不能自己構造。type info是實現相關的,不同編譯工具鏈的實現可能不一致。下面的 可以列印出int型別的名字 const st...