Micsorft文档阅读笔记-Run-Time Type Information解析及使用
生活随笔
收集整理的這篇文章主要介紹了
Micsorft文档阅读笔记-Run-Time Type Information解析及使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
官方解析
博主栗子
官方解析
Run-Time Type Information解析
Run-time type information (RTTI)運行時類型信息是一個運行機制,這個機制是在程序執行期間要明確一個對象的類型。RTTI在C++中被使用的原因是許多類或者框架實現了很多功能,這就會造成類庫間的不兼容。因此,RTTI解決了在語言層面上類庫兼容問題。
RTTI幾乎都是針對限制于指針問題。然而,討論的概念也適用于引用。
RTTI在C++中主要的三種情況:
1.dynamic_cast操作符:使用多態類型的轉換;
2.typeid操作符:用于識別這個類的具體類型;
3.type_info類:用于保護typeid這個操作符返回后的類型信息;
?
博主栗子
源碼一:
#include <iostream> using namespace std;class Base { public:void print() {cout << "Base print() called!\n";} };class Child :public Base { public:void print() {cout << "Child print() called!\n";} };void main() {Child *child = new Child;child->print();Base *base = dynamic_cast<Child*>(child); //or use it in this way//Base *base_2 = child;base->print();getchar(); }運行截圖如下:
源碼二:
#include <iostream> #include <typeinfo> using namespace std;class Base { public:void print() {cout << "Base print() called!\n";} };class Child :public Base { public:void print() {cout << "Child print() called!\n";} };void main() {cout << typeid(1).name() << endl;cout << typeid(1.1).name() << endl;cout << typeid(new Base).name() << endl;cout << typeid(*new Base).name() << endl;Child *child = new Child;Base *base = child;cout << typeid(base).name() << endl;cout << typeid(*base).name() << endl;getchar(); }運行截圖如下:
補充:typeid是在編譯時期識別的,關于type_info將在以后的博文中給出
總結
以上是生活随笔為你收集整理的Micsorft文档阅读笔记-Run-Time Type Information解析及使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt工作笔记-QGraphics重设场景
- 下一篇: Qt文档阅读笔记-QThread::se