C++ 程式中的 RTTI(執行時型別資訊)
在本文中,我們將學習 C++ 中的 RTTI(執行時型別資訊)。在 C++ 中,RTTI 是一個機制,可在執行時公開有關物件的資料型別的資訊。僅當類至少有一個虛擬函式時,此功能才可用。它允許在程式執行時確定物件的型別。
在以下示例中,第一段程式碼將不起作用。它會生成類似於“無法將 base_ptr(型別為 Base*)動態轉換為型別‘class 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP