C++提供了一个type_info类来获取对象类型信息,具有如下特点:
(1)这个类的构造函数是private的,因此用户不能直接构造这样的对象,只能通过typeid()函数来获取这个对象.
(2)这个类对外提供了name(),operator==()等方法供用户使用.
(3)typeid()可以对基本的数据类型和对象进行操作,这种情况下,是在编译期静态决定的.如:
typeid(int);
int a; typeid(a);
(4)type_info也可以对类类型和类对象进行操作,分两种情况:如果是声明了虚函数的类对象引用,则typeid()返回的是实际对象的类型信息,在运行时动态决定的;反之(没有定义虚函数,或者即使定义了虚函数但传入的是对象指针),则typeid()返回的是入参声明类型信息,在编译时静态决定的.
示例代码如下:
(1)基本数据类型示例:
#include <iostream>
#include <typeinfo>
using namespace std;
int main(void) {
// Basic data type
char a = 'a';
short b = 10;
int c = 99;
long d = 20;
float e = 2.3;
double f = 4.8;
cout << typeid(char).name() << endl;
cout << typeid(a).name() << endl;
cout << typeid(short).name() << endl;
cout << typeid(b).name() << endl;
cout << typeid(int).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(long).name() << endl;
cout << typeid(d).name() << endl;
cout << typeid(float).name() << endl;
cout << typeid(e).name() << endl;
cout << typeid(double).name() << endl;
cout << typeid(f).name() << endl;
if (typeid(f) == typeid(double)) {
cout << "type is equal" << endl;
} else {
cout << "type is not equal" << endl;
}
return 0;
}
运行结果:
c
c
s
s
i
i
l
l
f
f
d
d
type is equal
(2)无虚函数示例代码:
#include <iostream>
#include <typeinfo>
using namespace std;
class Base {
public:
void func() {cout << "Base::func()" << endl;};
};
class Derived: public Base {
};
int main(void) {
Derived derived;
Base base, *pbase, &rbase = derived;
pbase = &derived;
cout << typeid(base).name() << endl;
cout << typeid(derived).name() << endl;
cout << typeid(pbase).name() << endl;
cout << typeid(rbase).name() << endl;
return 0;
}
运行结果:
4Base
7Derived
P4Base
4Base
(3)有虚函数示例代码:
#include <iostream>
#include <typeinfo>
using namespace std;
class Base {
public:
virtual void func() {cout << "Base::func()" << endl;};
};
class Derived: public Base {
};
int main(void) {
Derived derived;
Base base, *pbase, &rbase = derived;
pbase = &derived;
cout << typeid(base).name() << endl;
cout << typeid(derived).name() << endl;
cout << typeid(pbase).name() << endl;
cout << typeid(rbase).name() << endl;
return 0;
}
运行结果:
4Base
7Derived
P4Base
7Derived