C++ 中的 RTTI(執行時型別資訊)
在本節中,我們來看一下 C++ 中的 RTTI(執行時型別資訊)。在 C++ 中,RTTI 是一種機制,它可以在執行時顯示有關物件資料型別的資訊。此功能僅當類至少有一個虛擬函式時才可用。它允許在程式執行時確定物件的型別。
在以下示例中,第一個程式碼將無法執行。它將生成一個錯誤,例如“無法將 base_ptr(型別為 Base*)動態轉換為型別'類 Derived*'(源型別不是多型的)”。出現此錯誤的原因是此示例中沒有虛擬函式。
示例程式碼
#include<iostream> using namespace std; class Base { }; class Derived: public Base {}; int main() { Base *base_ptr = new Derived; Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr); if(derived_ptr != NULL) cout<<"It is working"; else cout<<"cannot cast Base* to Derived*"; return 0; }
現在,在添加了虛擬方法後,它將可以工作。
示例程式碼
#include<iostream> using namespace std; class Base { virtual void function() { //empty function } }; class Derived: public Base {}; int main() { Base *base_ptr = new Derived; Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr); if(derived_ptr != NULL) cout<<"It is working"; else cout<<"cannot cast Base* to Derived*"; return 0; }
輸出
It is working
廣告