基类使用virtual 后子类可以省略不写,但是仍然存在,建议不这样写
#include "pch.h"
#include <iostream>
using namespace std;
class A
{
public:
virtual void base()
{
cout << "base A" << endl;
}
};
class B :public A
{
public :
void base()
{
cout << "base B" << endl;
}
};
int main()
{
A a;
B b;
a.base();
b.base();
A *p1 = new A;
B *p2 = new B;
p1->base();
p2->base();
// B *p3 = new A; 错误
// p3->base();
A *p4 = new B; // 多态的实现(其中的一中),基类可以调用子类的函数
p4->base();
system("pause");
std::cout << "Hello World!\n";
}
结果:
base A
base B
base A
base B
base B
请按任意键继续. . .
注释:最后一个可以看到结果(多态),上述代码会出现内存泄露的问题,就不改了。故意留下,原因是虚析构函数