typeid运算符可用于指出某一数据的类型。当基础类别里有虚拟函数,则此基础类别的指针(参考)指向衍生类别对象时,typeid将可指出实际指向的对象的类型名称。
typeid运算符的语法如下:
typeid(算式)
返回值为指向const type_info对象的参考,此对象将表达出类型的代号。
以下程序将利用typeid判别a变量是否为整数类型。
int a ;
if( typeid (a) == typeid(int)) ...
如果要取得数据类型的名称,则课通过typeid运算符所返回的type_info对象参考声明name成员函数:
typeid(算式).name()
返回值为类型名称的字符串,以下程序将取得a变量的类型名称:
char * data_type = typeid (a).name()
typeid运算符除了可以运用与判断指向衍生类别的基础类别指针(参考)外,还可以运用于模板类别与模板函数,判断套用模板的数据类型。
#include <iostream>
#include <typeinfo>
using namespace std;
class Base
{
public:
virtual void show()
{
cout << "base :: show() is called! " << endl;
}
};
class Derived: public Base
{
public:
void show()
{
cout << "derived :: show() is called! " <<endl;
}
};
int main()
{
Base * base_ptr = new Derived;
//判断base-ptr指针指向对象的类型是否为Derived类别
if(typeid(*base_ptr) == typeid(Derived))
{
cout << typeid(*base_ptr).name << endl;
//声明type_info类别的name成员函数,取得base_ptr指针指向对象的名称
}
//显示base_ptr指针的类型
cout << "base_ptr的类型是:" << typeid(base_ptr).name() <<endl;
return 0;
}