目录
一.name操作
1.语法:
typeid(data).name();
填入参数,参数可以是数据类型也可以是数据,该函数以C风格的字符串指针形式返回该数据的类型名。
2.示例:
C++代码:
#include<iostream>
#include<vector>
#include<list>
#include<string>
#include<map>
#include<typeinfo>
using namespace std;
class example
{
private:
string name;
};
int main()
{
int a;
int* ptr;
vector<string> vec;
list<int> lis;
string str;
map<string, int> m1;
example e1;
//typeid(data).name();
cout << "int is:" << typeid(int).name() << endl;
cout << "-------------------" << endl;
cout << "a is:" << typeid(a).name() << endl;
cout << "-------------------" << endl;
cout << "ptr is:" << typeid(ptr).name() << endl;
cout << "-------------------" << endl;
cout << "vec is:" << typeid(vec).name() << endl;
cout << "-------------------" << endl;
cout << "lis is:" << typeid(lis).name() << endl;
cout << "-------------------" << endl;
cout << "str is:" << typeid(str).name() << endl;
cout << "-------------------" << endl;
cout << "m1 is:" << typeid(m1).name() << endl;
cout << "-------------------" << endl;
cout << "e1 is:" << typeid(e1).name() << endl;
cout << "-------------------" << endl;
system("pause");
return 0;
}
程序运行结果:
二.!=和==操作
1.语法:
typeid(data1) == typeid(data2);
typeid(data3) != typeid(data4);
判断两个数据是否相同,参数可以是数据类型也可以是数据
2.示例:
C++代码:
#include<iostream>
#include<typeinfo>
#include<string>
using namespace std;
class base
{
};
class derive :public base
{
};
int main()
{
base b1;
derive d1;
if (typeid(b1) == typeid(base))
{
cout << "b1 is a base" << endl;
}
if (typeid(d1) != typeid(base))
{
cout << "d1 is not a base" << endl;
}
if (typeid(d1) == typeid(derive))
{
cout << "d1 is a derive" << endl;
}
string name;
if (typeid(name) == typeid(string))
{
cout << "name is a string" << endl;
}
system("pause");
return 0;
}
程序运行结果:
三.总结说明
1.和sizeof这类的操作符一样,typeid是C++的关键字之一。
2.typeid操作符的返回结果是名为type_info的标准库类型的对象的引用(在头文件typeinfo中定义)3.typeid(*this) -- 返回一个type_info对象,关联至this指针所指对象
4.C++并没有规定typeid实现标准,各个编译器可能会不一样。
5.编译器会为每一种typeid操作的类型生成一份保存在数据段的type_info数据。
6.每种类型的type_info数据长度依赖于类型名称,至少9个字节。7.typeid运算符会返回一个type_info对象,其中储存着与类型相关的种种信息。