需要虚拟函数覆盖来使用override关键字 [英] Requiring virtual function overrides to use override keyword
问题描述
C ++ 11添加了覆盖
,以确保您编写的成员函数旨在覆盖基类虚拟函数实际上做(或不会编译)。
C++11 added override
to ensure that member functions you write that you intend to override base-class virtual functions actually do (or won't compile).
但是在一个大对象层次结构中,有时你可能会意外地写一个成员函数,当你不打算覆盖一个基类虚拟。例如:
But in a large object hierarchy, sometimes you could accidentally end up writing a member function that overrides a base-class virtual when you didn't intend it. For instance:
struct A {
virtual void foo() { } // because obv every class has foo().
};
struct B : A { ... };
class C : B {
private:
void foo() {
// was intended to be a private function local to C
// not intended to override A::foo(), but does
}
};
是否有一些编译器标志/扩展,至少会在 C :: foo
?为了可读性和正确性,我只是想强制所有的覆盖使用 override
。
Is there some compiler flag/extension that would at least issue a warning on C::foo
? For readability and correctness, I just would like to enforce that all overrides use override
.
推荐答案
看起来像GCC 5.1版本完全添加了我正在查找的警告:
-Wsuggest-override
警告覆盖未使用override关键字标记的虚拟函数。
-Wsuggest-override
Warn about overriding virtual functions that are not marked with the override keyword.
使用 -Wsuggest-override
编译 -Werror = suggest-override
会强制所有覆盖使用 override
。
Compiling with -Wsuggest-override
-Werror=suggest-override
would then enforce that all overrides use override
.
这篇关于需要虚拟函数覆盖来使用override关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!