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

时间:2016-03-16 11:30:51

标签: c++ c++11 inheritance virtual

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

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;
};

我没有看到Prefixing virtual keyword to overridden methods回答了我的问题。特别是,其中一个答案已更新,以反映c ++ 11的当前用法,特别是我不知道的override关键字!

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

3 个答案:

答案 0 :(得分:9)

Nowadays, it's better to mark them as override. It tells the reader the function is virtual, and is also a fail-safe mechanism (in case you get the signature wrong).

I'd only use virtual if that was consistent with already existing code.

class LevelOne : public Base {
protected:
   void to_be_derived() const override;
   //                            |
   // clearly virtual, certain it's the same signature as the base class
};

答案 1 :(得分:-1)

最好将它们标记为虚拟和覆盖。虚拟将阻止您为传递的对象调用错误的函数。覆盖将防止您在签名中出错,并使代码更具可读性。 正如Scott Meyers在有效的c ++书中所写,你不应该在delevired classes中重新定义非虚函数。

答案 2 :(得分:-2)

Base Class Virtual会强制继承类,即LevelOne覆盖它。

除非您需要LevelTwo来覆盖LevelOne的实现,否则您无需将其标记为虚拟。

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