首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

虚函数在衍生的时候被覆盖之后再次派生就不能覆盖这个虚函数了么

2013-09-04 
虚函数在派生的时候被覆盖之后再次派生就不能覆盖这个虚函数了么?#include iostream#include string#i

虚函数在派生的时候被覆盖之后再次派生就不能覆盖这个虚函数了么?

#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
B::g
D::f
B::g
D::f
B::g

B::f
B::g
D::f
D::g
DD:f
DD::g
《C++程序设计原理与实践》中文版第301页,14.3.3。代码有的地方我改了,但基本意思没变。

有什么办法能在DD中继续覆盖D中的f()么?
[解决办法]
你DD的f没有const,所以和基类的f是完全两个不同的函数,只是名字相同。因此是隐藏了基类f而不是重写基类f。

热点排行