typeid運算符能獲取類型信息。獲取到的是type_info對象。type_info類型如下:
可以看到,這個類刪除了拷貝構造函數以及等號操作符。有一些成員函數:hash_code、before、name、raw_name,? 還重載了==和!=運算符。
測試:
void testTypeId() {//獲取一個普通變量的類型信息unsigned int n = 9527;const type_info& nInfo = typeid(n); // 得到type_info 對象std::cout << "普通變量的類型信息:" << nInfo.name() << " | " << nInfo.raw_name() << " | " << nInfo.hash_code() << endl;//獲取一個普通類型的類型信息const type_info& charInfo = typeid(char);std::cout << "普通類型的類型信息:" << charInfo.name() << " | " << charInfo.raw_name() << " | " << charInfo.hash_code() << endl;//獲取一個字面量的類型信息const type_info& dInfo = typeid(95.27);std::cout << "字面量的類型信息:" << dInfo.name() << " | " << dInfo.raw_name() << " | " << dInfo.hash_code() << endl;class Base {};struct MyStruct {};//獲取一個對象的類型信息Base obj;const type_info& objInfo = typeid(obj);std::cout << "對象的類型信息:" << objInfo.name() << " | " << objInfo.raw_name() << " | " << objInfo.hash_code() << endl;//獲取一個結構體的類型信息const type_info& stuInfo = typeid(struct MyStruct);std::cout << "結構體的類型信息:" << stuInfo.name() << " | " << stuInfo.raw_name() << " | " << stuInfo.hash_code() << endl;//獲取一個表達式的類型信息const type_info& expInfo = typeid(9528 - 1);std::cout << "表達式的類型信息:" << expInfo.name() << " | " << expInfo.raw_name() << " | " << expInfo.hash_code() << endl;
}
打印:
typeid運算符能用于類型比較。
基本類型比較,代碼:
// 測試基本類型:
char* str;
int a = 9527;
int b = 1;
float f;
std::cout << "typeid(int) == typeid(int) ? " << (typeid(int) == typeid(int)) << endl;
std::cout << "typeid(int) == typeid(char) ? " << (typeid(int) == typeid(char)) << endl;
std::cout << "typeid(char) == typeid(char*) ? " << (typeid(char) == typeid(char*)) << endl;
std::cout << "typeid(str) == typeid(char*) ? " << (typeid(str) == typeid(char*)) << endl;
std::cout << "typeid(a) == typeid(int) ? " << (typeid(a) == typeid(int)) << endl;
std::cout << "typeid(a) == typeid(b) ? " << (typeid(a) == typeid(b)) << endl;
std::cout << "typeid(a) == typeid(f) ? " << (typeid(a) == typeid(f)) << endl;
std::cout << "typeid(a - b) == typeid(int) ? " << (typeid(a - b) == typeid(int)) << endl;
打印:
類的比較,代碼:
// 類的比較:
class Sub : public Base {};
Base obj1;
Base* p1;
Sub obj2;
Sub* p2 = new Sub;
p1 = p2;
std::cout << "typeid(obj1) == typeid(p1) ? " << (typeid(obj1) == typeid(p1)) << endl;
std::cout << "typeid(obj1) == typeid(*p1) ? " << (typeid(obj1) == typeid(*p1)) << endl;
std::cout << "typeid(obj1) == typeid(obj2) ? " << (typeid(obj1) == typeid(obj2)) << endl;
std::cout << "typeid(p1) == typeid(Base*) ? " << (typeid(p1) == typeid(Base*)) << endl;