C.128: Virtual functions should specify exactly one of virtual, override, or final
C.128:虚函数应该明确定义为virtual,overide或者final
Reason(原因)
Readability. Detection of mistakes. Writing explicit virtual, override, or final is self-documenting and enables the compiler to catch mismatch of types and/or names between base and derived classes. However, writing more than one of these three is both redundant and a potential source of errors.
virtual means exactly and only "this is a new virtual function."
virual明确表示而且只用于表示"这是一个新的虚函数"
override means exactly and only "this is a non-final overrider."
overide明确表示而且只表示“这不是最终覆盖者”
final means exactly and only "this is a final overrider."
final明确表示而且只用于表示“这是最终覆盖者”
Example, bad(反面示例)
struct B {
void f1(int);
virtual void f2(int) const;
virtual void f3(int);
// ...
};
struct D : B {
void f1(int); // bad (hope for a warning): D::f1() hides B::f1()
void f2(int) const; // bad (but conventional and valid): no explicit override
void f3(double); // bad (hope for a warning): D::f3() hides B::f3()
// ...
};
We want to eliminate two particular classes of errors:
我们希望排除两类特殊的错误:
implicit virtual: the programmer intended the function to be implicitly virtual and it is (but readers of the code can't tell); or the programmer intended the function to be implicitly virtual but it isn't (e.g., because of a subtle parameter list mismatch); or the programmer did not intend the function to be virtual but it is (because it happens to have the same signature as a virtual in the base class)
implicit override: the programmer intended the function to be implicitly an overrider and it is (but readers of the code can't tell); or the programmer intended the function to be implicitly an overrider but it isn't (e.g., because of a subtle parameter list mismatch); or the programmer did not intend the function to be an overrider but it is (because it happens to have the same signature as a virtual in the base class -- note this problem arises whether or not the function is explicitly declared virtual, because the programmer may have intended to create either a new virtual function or a new nonvirtual function)