typeid操作符

来源:互联网 发布:人大 网络教育二学位 编辑:程序博客网 时间:2024/05/17 07:11

typeid是C++的一个操作符。

typeid操作符的返回结果是名为type_info,ISO C++标准并没有确切定义type_info,它的确切定义编译器相关的。

  • typeid(基类指针),则表示此指针;

       基类至少有一个virtual类型函数,则:
  • typeid(*基类指针),则表示此指针所指对象的实际类型,可以得到派生类的类型;
  • typeid(基类引用),则可以得到派生类的类型;

#include <iostream>using namespace std;class base{public:virtual ~base(){} -------- 基类至少得有一个virtual函数,也可以是virtual函数,才能typeid(*pb)获取实际所指内容类型,否则返回基类类型。};class test : public base{};int main(){   base *pb=new test;   base b;   cout << typeid(pb).name() << endl;   cout << typeid(*pb).name() << endl;   cout << typeid(b).name() << endl;}


输出为
P4base
4test
4base