typeid是C++中RTTI(Run-TimeType Information, 运行时类型识别)机制的组成部分,其目的是根据传入已有的参数,来判断参数的数据类型。
对于基本数据类型的用法与运行结果(g++ 6.3.0):
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int a = 0;
float b = 0;
double c = 0;
char d = 0;
cout << typeid(int).name()<< endl;
cout << typeid(a).name()<< endl;
cout << typeid(float).name()<< endl;
cout << typeid(b).name()<< endl;
cout << typeid(double).name()<< endl;
cout << typeid(c).name()<< endl;
cout << typeid(char).name()<< endl;
cout << typeid(d).name()<< endl;
cout << typeid(&d).name()<< endl;
}
运行结果:
leo@leo-X550JD:~$ ./a.out
i
i
f
f
d
d
c
c
Pc
对于类中的用法和运行结果(g++ 6.3.0):
#include <iostream>
#include <typeinfo>
using namespace std;
//基类
class Base
{
public:
Base()
{
//Base
}
~Base(){};
};
//派生类
class Person : public Base
{
public:
Person()
{
//Person
}
~Person(){};
};
int main()
{
Base a;
Person b;
Base *c = new Person;
cout << typeid(Base).name() << endl;
cout << typeid(a).name() << endl
<< endl;
cout << typeid(Person).name() << endl;
cout << typeid(b).name() << endl
<< endl;
cout << typeid(Base*).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(*c).name() << endl
<< endl;
}
运行结果:
4Base
4Base
6Person
6Person
P4Base
P4Base
4Base
其中,P开头的是指针类型。