一、typeid的概念
C++里的typeid是運算符,可以獲取一個表達式的類型信息。它的返回值是一個類型信息的引用類型,表示該表達式的數據類型。
// 示例代碼 #include <iostream> #include <typeinfo> using namespace std; int main() { int a = 0; double b = 1.0; const string c = "hello"; cout << typeid(a).name() << endl; cout << typeid(b).name() << endl; cout << typeid(c).name() << endl; return 0; }
運行以上代碼,輸出如下:
i
d
NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
可以看到輸出的內容都是類型信息,分別對應int類型、double類型和string類型。
二、typeid的使用
C++里的typeid可以用於不同的場景,本節將會介紹一些常見的使用方式。
1. typeid與指針
使用typeid獲取指針所指向的類型信息。
// 示例代碼 #include <iostream> #include <typeinfo> using namespace std; int main() { int a = 0; double b = 1.0; const string c = "hello"; cout << typeid(&a).name() << endl; cout << typeid(&b).name() << endl; cout << typeid(&c).name() << endl; return 0; }
運行以上代碼,輸出如下:
Pi
Pd
PKc
可以看到輸出的內容都是指針類型信息。
2. typeid與多態及繼承
運用typeid可以方便地獲取對象的類型信息,在多態及繼承的場景下特別有用。
示例代碼如下:
// 示例代碼 #include <iostream> #include <typeinfo> using namespace std; class Animal { public: virtual void speak() {} }; class Cat : public Animal { public: virtual void speak() { cout << "I'm a cat." << endl; } }; class Dog : public Animal { public: virtual void speak() { cout << "I'm a dog." << endl; } }; void outputType(Animal* a) { if (typeid(*a) == typeid(Cat)) { cout << "Cat" << endl; } else if (typeid(*a) == typeid(Dog)) { cout << "Dog" << endl; } } int main() { Cat c; Dog d; Animal* a1 = &c; Animal* a2 = &d; outputType(a1); outputType(a2); return 0; }
運行以上代碼,輸出如下:
Cat
Dog
可以看到在outputType()中使用了typeid來判斷傳入的指針的類型,並輸出類型名稱。
三、typeid的局限性
雖然使用typeid可以方便地獲取對象的類型信息,但是在某些場景下會受到其局限性的影響。
1. typeid與基本類型
在基本類型(例如int、double等)的場景下,typeid無法提供具體的類型信息。
// 示例代碼 #include <iostream> #include <typeinfo> using namespace std; int main() { int i = 0; double d = 1.0; cout << typeid(i).name() << endl; cout << typeid(d).name() << endl; return 0; }
運行以上代碼,輸出如下:
i
d
可以看到輸出的內容只包含類型信息,無法提供有用信息。
2. typeid與泛型
在虛擬函數和泛型編程中,使用typeid也會受到一定的限制。
// 示例代碼 #include <iostream> #include <typeinfo> using namespace std; template <typename T> void printType(T t) { cout << typeid(t).name() << endl; } int main() { int i = 0; double d = 1.0; const string c = "hello"; printType(i); printType(d); printType(c); return 0; }
運行以上代碼,輸出如下:
i
d
NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
可以看到在使用模板函數時,typeid的顯示方式與普通的方法有所不同,無法直接獲取類型名稱。
四、總結
C++中的typeid可以方便地獲取類型信息,與面向對象編程的多態機制和繼承機制相輔相成,在某些場景下使用效果明顯。但值得注意的是,typeid也存在一些局限性,比如在基本類型和泛型編程的場景下效果不佳,需要開發者在使用時進行注意。
原創文章,作者:ZGAMC,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/318040.html