c++ - 虚函数不会覆盖最新的继承对象
问题描述
我有 3 个班级:A,B,C。B继承自A,C继承自B(因此C是A的孙子)。
每个对象都有显示文本的函数talk(),在A和B中它是虚拟的。
让外部函数call( A &a),它通过引用获取对象A ,并调用函数talk()。
将对象C发送到函数,它使用B中的talk()而不是C,即使在B talk()是虚拟的。
为什么会这样?如何使它从C调用版本?
#include <iostream>
using namespace std;
class A {
public:
virtual void talk() = 0;
virtual void say() = 0;
};
class B : public A {
public:
virtual void talk() // Why C does not overrides this?
{ cout << "hello\n"; }
};
class C : public B {
public:
void talk (int a) // It should override B.talk();
{ cout << "bye\n";}
virtual void say() { cout << "my name\n"; }
};
void call(A &a) {
a.talk(); // Why does it call virtual talk() from B rather than from C?
a.say(); // This was found so it knows about object C
}
int main() {
C c;
call(c);
system("PAUSE");
return 0;
}
如果每个类之间都有虚拟talk(),我希望call(A &a)采用最远的继承版本
解决方案
在您的示例中,C.talk(int)
不会覆盖B.talk()
,因为C.talk
将 int 作为参数,因此它是一个完全不同的函数。
您可以override
在函数声明之后添加以使编译器检查它是否实际上覆盖了任何内容:
class C : public B {
public:
// Here, the compiler complains because there's no talk(int) method
// That it can override
void talk (int a) override;
{ cout << "bye\n";}
virtual void say() { cout << "my name\n"; }
};
推荐阅读
- python - 将 sympy 符号变量转换为 numpy 数组
- javascript - 重定向到另一个页面 React-Native
- c# - 无法在 AutoFac 中注册 ITypeConverter
- android - Recycler ItemDecoration item出现在recycler view items上
- c++ - 使用 Nuget 在 Visual Studio 2019 中安装 Boost v1.70
- android - exoplayer出错时如何跳过播放列表中的MP4视频
- java - 创建.jar文件idea项目命令行
- javascript - 使用表单元素显示时钟
- angular6 - 使用 ng2-pdfjs-viewer 使用 s3 签名的 url 显示 pdf
- python - Matplotlib-cpp:ImportError:没有名为站点的模块