首页 > 代码库 > C++获取基类指针所指子类对象的类名

C++获取基类指针所指子类对象的类名

我们在程序中定义了一个基类,该基类有n个子类,为了方便,我们经常定义一个基类的指针数组,数组中的每一项指向都指向一个子类,那么在程序中我们如何判断这些基类指针是指向哪个子类呢?

关键字

typeid,有关此关键字的详细内容请自行百度。

代码:

 1 #include <iostream> 2 #include <string> 3 #include <typeinfo> 4 using namespace std; 5  6 class father 7 { 8 public: 9     virtual void fun()10     {11         cout<<"this is father fun call\n";12     }13     virtual int id()14     {15         return 0;16     }17 };18 19 class son1: public father20 {21 public:22 23     void fun()24     {25         cout<<"this is the son1 fun call\n";26     }27 28     int id()29     {30         return 1;31     }32 33 };34 35 class son2: public father36 {37 public:38 39     void fun()40     {41         cout<<"this is the son2 fun call\n";42     }43 44     int id()45     {46         return 2;47     }48 };49 50 int main()51 {52     father * pf;53     son1 s1;54     son2 s2;55     pf = &s1;56     cout << typeid(*pf).name() <<endl;57     string temp(typeid(*pf).name());58     if(temp == "class son1")59     {60         cout<<"this is son1\n";61     }62     else if(temp == "class son2")63     {64         cout<<"this is son2\n";65     }66 67     pf = &s2;68     cout << typeid(*pf).name() <<endl;69     string temp1(typeid(*pf).name());70     if(temp1 == "class son1")71     {72         cout<<"this is son1\n";73     }74     else if(temp1 == "class son2")75     {76         cout<<"this is son2\n";77     }78     return 0;79 }

 

C++获取基类指针所指子类对象的类名