C++中的类型识别
文章目錄
- 1 C++中的類型識別
- 1.1 類型識別的基本概念
- 1.2 利用多態(tài)得到動態(tài)類型
- 1.3 typeid關(guān)鍵字
1 C++中的類型識別
1.1 類型識別的基本概念
在面向?qū)ο笾锌赡艹霈F(xiàn)下面的情況:
- 基類指針指向子類對象。
- 基類引用成為子類對象的別名。
靜態(tài)類型和動態(tài)類型的概念:
- 靜態(tài)類型:變量(對象)自身的類型。
- 動態(tài)類型:指針(引用)所指向?qū)ο蟮膶嶋H類型。
1.2 利用多態(tài)得到動態(tài)類型
利用多態(tài)得到動態(tài)類型:
編程實驗:動態(tài)類型識別
#include <iostream> #include <string>using namespace std;class Base { public:virtual string type(){return "Base";} };class Derived : public Base { public:string type(){return "Derived";}void printf(){cout << "I'm a Derived." << endl;} };class Child : public Base { public:string type(){return "Child";} };void test(Base* b) {/* 危險的轉(zhuǎn)換方式 */// Derived* d = static_cast<Derived*>(b);if( b->type() == "Derived" ){Derived* d = static_cast<Derived*>(b);d->printf();}// cout << dynamic_cast<Derived*>(b) << endl; }int main(int argc, char *argv[]) {Base b;Derived d;Child c;test(&b);test(&d);test(&c);return 0; }動態(tài)解決方案的缺陷:
- 必須從基類開始提供類型虛函數(shù)。
- 所有的派生類都必須重寫類型虛函數(shù)。
- 每個派生類的類型名必須唯一。
1.3 typeid關(guān)鍵字
C++提供了typeid關(guān)鍵字用于獲取類型信息:
- typeid關(guān)鍵字返回對應(yīng)參數(shù)的類型信息。
- typeid返回一個type_info類對象。
- 當(dāng)typeid的參數(shù)為NULL時將拋出異常。
typeid關(guān)鍵字的使用:
typeid的注意事項:
- 當(dāng)參數(shù)為類型時:返回靜態(tài)類型信息。
- 當(dāng)參數(shù)為變量時:
- 不存在虛函數(shù)表時,返回靜態(tài)類型信息。
- 存在虛函數(shù)表,返回動態(tài)類型信息。
編程實驗:typeid類型識別
#include <iostream> #include <string> #include <typeinfo>using namespace std;class Base { public:virtual ~Base(){} };class Derived : public Base { public:void printf(){cout << "I'm a Derived." << endl;} };void test(Base* b) {const type_info& tb = typeid(*b);cout << tb.name() << endl; }int main(int argc, char *argv[]) {int i = 0;const type_info& tiv = typeid(i);const type_info& tii = typeid(int);cout << (tiv == tii) << endl;Base b;Derived d;test(&b);test(&d);return 0; }參考資料:
總結(jié)
- 上一篇: C语言中的异常处理
- 下一篇: 什么是云计算概念股 这些你得了解