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

gre*_*iod 1 c++ virtual inheritance c++11

在任何级别的后代类中,显式标记为虚拟是否都会覆盖?

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;
};
Run Code Online (Sandbox Code Playgroud)

我没有看到Prefixing虚拟关键字覆盖了我的问题的覆盖方法.特别是,其中一个答案已更新,以反映c ++ 11的当前用法,特别override是我不知道的关键字!

编辑:我宁愿接受关于post-c ++ 11代码的链接问题的另一个答案.

Luc*_*ore 9

如今,将它们标记为更好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
};
Run Code Online (Sandbox Code Playgroud)

  • 事实上,@ greendiod,如果你使用覆盖并且基本版本不是虚拟的,你将收到错误. (2认同)