虚函数在派生的时候被覆盖之后再次派生就不能覆盖这个虚函数了么?
#include <iostream>结果:
#include <string>
#include <cstdlib>
using namespace std;
struct B
{
virtual void f() const { cout << "B::f" << endl; }
void g() const { cout << "B::g" << endl; }
};
struct D: B
{
void f() const { cout << "D::f" << endl; }
void g() { cout << "D::g" << endl; }
};
struct DD: D
{
void f() { cout << "DD:f" << endl; }
void g() const { cout << "DD::g" << endl; }
};
void call( const B& b )
{
b.f();
b.g();
}
int main()
{
B b;
D d;
DD dd;
call( b );
call( d );
call( dd );
cout << endl;
b.f();
b.g();
d.f();
d.g();
dd.f();
dd.g();
system( "pause" );
return 0;
}
B::f《C++程序设计原理与实践》中文版第301页,14.3.3。代码有的地方我改了,但基本意思没变。
B::g
D::f
B::g
D::f
B::g
B::f
B::g
D::f
D::g
DD:f
DD::g