应该在所有继承级别还是仅在祖先级别声明虚拟函数

Should one declare functions virtual at all levels of inheritance or only at the ancestor level?

本文关键字:祖先 声明 虚拟 函数 继承      更新时间:2023-10-16

是否应该在任何级别的后代类中将所有覆盖显式标记为虚拟?

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的实现,否则你不需要将其标记为虚拟。

通常,除非派生类必须重写它,否则不需要使用虚拟