C++中提供了typeid关键字用于获取类型信息,其返回值为type_info类对象,当typeid的参数为NULL是直接返回异常。typeid返回类型注意:
- 当参数为类型时,返回静态类型信息
- 当参数为变量是,如果变量不存在虚拟函数表,返回静态类型信息;如果存在虚函数表,返回动态类型信息
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
class Base
{
public:
virtual ~Base()
{
}
};
class Derived : public Base
{
public:
void printf()
{
cout << "I'm a Derived." << endl;
}
};
void test(Base* b)
{
const type_info& tb = typeid(*b);
cout << tb.name() << endl;
}
int main(int argc, char *argv[])
{
int i = 0;
const type_info& tiv = typeid(i);
const type_info& tii = typeid(int);
cout << (tiv == tii) << endl;
Base b;
Derived d;
test(&b);
test(&d);
return 0;
}
|