typeid 判斷對象類型是否一致

在編寫程序中,有時候需要判斷兩個對象是不是同一個類型,就需要用到typeid,通常有些人喜歡用type( obj ).name()去進行字符串的比較,這種比較方式的開銷是比較大的。在此,儘量使用hash_code()去進行比較,如下所示。

#include <iostream>
# include <typeinfo>
using namespace std; 

class A{};
class B{};
int main(int argc, char** argv)
{

	cout << "sizeof(A)::" << sizeof(A)<<endl;
	cout << "sizeof(B)::" << sizeof(B) << endl;

	A a;
	B b;
	
	cout << typeid(a).name() << endl; // 
	cout << typeid(b).name() << endl; // 
	A c;
	bool a_b= (typeid(a).hash_code() == typeid(b).hash_code());
	bool a_c = (typeid(a).hash_code() == typeid(c).hash_code());
	cout << "Are they consistent?" << endl;
	cout << "A and B:" << (int)a_b << endl; // 0
	cout << "A and C:" << (int)a_c << endl; // 1
	return 0;
}

A和B是空的,系統會爲class A和class B插入1字節。運行結果如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章