Do ALL virtual functions need to be implemented in derived classes?(所有的虚函数都需要在派生类中实现吗?)
问题描述
这似乎是一个简单的问题,但我在其他任何地方都找不到答案.
This may seem like a simple question, but I can't find the answer anywhere else.
假设我有以下内容:
class Abstract {
public:
virtual void foo() = 0;
virtual void bar();
}
class Derived : Abstract {
public:
virtual void foo();
}
Derived 类不实现 bar() 函数可以吗?如果不是我的所有派生类都需要 bar() 函数,但有些需要,该怎么办.抽象基类的所有虚函数都需要在派生类中实现,还是只需要在纯虚函数中实现?谢谢
Is it ok that class Derived does not implement the bar() function? What if not ALL of my derived classes need the bar() function, but some do. Do all of the virtual functions of an abstract base class need to be implemented in the derived classes, or just the ones that are pure virtual? Thanks
推荐答案
派生类不必自己实现所有虚函数.他们只需要实现 pure 的那些.1 这意味着问题中的 Derived
类是正确的.它继承其祖先类Abstract
的bar
实现.(这假设 Abstract::bar
在某处实现.问题中的代码声明了该方法,但没有定义它.您可以将其定义为 Trenki's answer 显示,或者您可以单独定义它.)
Derived classes do not have to implement all virtual functions themselves. They only need to implement the pure ones.1 That means the Derived
class in the question is correct. It inherits the bar
implementation from its ancestor class, Abstract
. (This assumes that Abstract::bar
is implemented somewhere. The code in the question declares the method, but doesn't define it. You can define it inline as Trenki's answer shows, or you can define it separately.)
1 即便如此,仅当派生类要实例化时.如果派生类没有直接实例化,而只是作为更多派生类的基类存在,那么负责实现所有纯虚方法的是那些那些类.层次结构中的中间"类允许保留一些未实现的纯虚拟方法,就像基类一样.如果中间"类确实实现了一个纯虚方法,那么它的后代将继承该实现,因此他们不必自己重新实现它.
1 And even then, only if the derived class is going to be instantiated. If a derived class is not instantiated directly, but only exists as a base class of more derived classes, then it's those classes that are responsible for having all their pure virtual methods implemented. The "middle" class in the hierarchy is allowed to leave some pure virtual methods unimplemented, just like the base class. If the "middle" class does implement a pure virtual method, then its descendants will inherit that implementation, so they don't have to re-implement it themselves.
这篇关于所有的虚函数都需要在派生类中实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:所有的虚函数都需要在派生类中实现吗?
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01