c语言虚表(C.128:虚函数应该明确定义为virtual)(1)

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,overide或者final本身就是一种说明,而且让编译器可以捕捉派生类和基类之间的类型或名称的不匹配问题。然而,使用这三个中的两个或三个就是多余的而且容易引发潜在的错误。

It's simple and clear(下面的规则简单又明快):

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() // ... };

Example, good(范例)

struct Better : B { void f1(int) override;        // error (caught): Better::f1() hides B::f1() void f2(int) const override; void f3(double) override;     // error (caught): Better::f3() hides B::f3() // ... };

Discussion(讨论)

We want to eliminate two particular classes of errors:

我们希望排除两类特殊的错误:

Enforcement(实施建议)

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c128-virtual-functions-should-specify-exactly-one-of-virtual-override-or-final


觉得本文有帮助?请分享给更多人。

更多精彩文章请关注微信公众号【面向对象思考】!

面向对象开发,面向对象思考!

,