应该在所有继承级别还是仅在祖先级别声明虚拟函数
Should one declare functions virtual at all levels of inheritance or only at the ancestor level?
是否应该在任何级别的后代类中将所有覆盖显式标记为虚拟?
class Base {
// ...
protected:
virtual void to_be_derived() const; // First level to introduce this virtual function
};
class LevelOne : public Base {
// ...
protected:
// virtual??
void to_be_derived() const;
};
class LevelTwo : public levelOne {
// ...
protected:
// virtual??
void to_be_derived() const;
};
我没有看到前缀虚拟关键字来覆盖我的问题。特别是,其中一个答案已更新以反映当前对 c++11 的使用情况,尤其是我不知道的override
关键字!
编辑:我宁愿接受后c ++ 11代码链接问题的另一个答案。
如今,最好将它们标记为 override
.它告诉读者该功能是虚拟的,也是一种故障安全机制(以防您错误地获取签名)。
我只会使用virtual
,如果它与已经存在的代码一致。
class LevelOne : public Base {
protected:
void to_be_derived() const override;
// |
// clearly virtual, certain it's the same signature as the base class
};
最好将它们标记为虚拟并覆盖。Virtual 将防止您为交付的对象调用错误的函数。 覆盖将防止您在签名中出错,并使代码更具可读性。正如 Scott Meyers 在有效的 c++ 书中所写的那样,你不应该在 delevired 类中重新定义非虚函数。
基
类虚拟将强制继承类即LevelOne覆盖它。
除非你需要LevelTwo来覆盖LevelOne的实现,否则你不需要将其标记为虚拟。
通常,除非派生类必须重写它,否则不需要使用虚拟
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- 应该在所有继承级别还是仅在祖先级别声明虚拟函数
- 前向声明从嵌套模板中隐藏祖先模板参数