第二个main函数你要把基类的函数声明为虚函数,这样它才会调用子类的函数!
#include<iostream>
using namespace std;
class A{
public:
virtual void print()//这里要加上virtual,说明是虚函数
{ cout<<"This is A"<<endl;}
};
class B:public A{
public:
void print()
{ cout<<"This is B"<<endl;}
};
int main(){
A a;
B b;
A* p1=&a;
A* p2=&b;
p1->print();
p2->print();
}