通过typeid打印派生类具体是哪一个

代码如下:

#include 
using namespace std;
class Base
{
public:
	virtual void fun() = 0; //此处有虚函数
};
class Derived1:public Base
{
	virtual void fun(){ cout << "this is Derived1 fun call\n"; };
};
class Derived2:public Base
{
	virtual void fun(){ cout << "this is Derived2 fun call\n"; };
};
class Derived3:public Base
{
	virtual void fun(){ cout << "this is Derived2 fun call\n"; };
};
int main()
{
    Base *p1 = new Derived1();
    cout << typeid(p1).name() << endl;
    cout << typeid(*p1).name() << endl; 
    p1 = new Derived2();
    cout << typeid(p1).name() << endl;
    cout << typeid(*p1).name() << endl;
    p1 = new Derived3();
    cout << typeid(p1).name() << endl;
    cout << typeid(*p1).name() << endl;  
	return 0;
}

结果如下:

P4Base
8Derived1
P4Base
8Derived2
P4Base
8Derived3

你可能感兴趣的:(C++编程,c++,算法,java)