我们来看代码来理解
#define CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class A {
public:
virtual void fun() {
cout << "A's fun" << endl;
}
};
class B :public A {
public:
void fun() {
cout << "B " << endl;
}
};
class C :public B {
void fun() {
cout << "C's fun" << endl;
}
};
int main()
{
C c;
B* p = &c;
p->fun();
return 0;
}
只要最顶层的类中的同名函数为虚函数,那么子类中所有同名函数都会被设置为虚函数