应该在所有继承级别或仅在祖先级别声明函数虚拟?
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;
};
我没有看到 Prefixing virtual keyword to overridden methods 回答我的问题。特别是,更新了其中一个答案以反映 c++11 的当前用法,尤其是我不知道的 override
关键字!
编辑:我宁愿接受 post-c++11 代码的链接问题的另一个答案。
如今,最好将它们标记为 override
。它告诉 reader 该函数是虚拟的,也是一种故障安全机制(以防您弄错签名)。
如果与现有代码一致,我只会使用 virtual
。
class LevelOne : public Base {
protected:
void to_be_derived() const override;
// |
// clearly virtual, certain it's the same signature as the base class
};
Base Class Virtual 会强制继承 class 即 LevelOne 覆盖它。
除非您需要 LevelTwo 覆盖 LevelOne 的实现,否则您不需要将其标记为虚拟。
一般情况下,除非派生class必须覆盖它,否则不需要使用virtual
最好将它们标记为虚拟并覆盖。 Virtual 将防止您为传递的对象调用错误的函数。 override 将防止您在签名中出错,并使代码更具可读性。
正如 Scott Meyers 在 effective c++ book 中所写,你不应该在 delevired 类 非虚函数中重新定义。
是否应明确标记为虚拟所有覆盖任何级别的后代 类?
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 代码的链接问题的另一个答案。
如今,最好将它们标记为 override
。它告诉 reader 该函数是虚拟的,也是一种故障安全机制(以防您弄错签名)。
如果与现有代码一致,我只会使用 virtual
。
class LevelOne : public Base {
protected:
void to_be_derived() const override;
// |
// clearly virtual, certain it's the same signature as the base class
};
Base Class Virtual 会强制继承 class 即 LevelOne 覆盖它。
除非您需要 LevelTwo 覆盖 LevelOne 的实现,否则您不需要将其标记为虚拟。
一般情况下,除非派生class必须覆盖它,否则不需要使用virtual
最好将它们标记为虚拟并覆盖。 Virtual 将防止您为传递的对象调用错误的函数。 override 将防止您在签名中出错,并使代码更具可读性。 正如 Scott Meyers 在 effective c++ book 中所写,你不应该在 delevired 类 非虚函数中重新定义。