c++核心准则C.137: 使用虚基类避免过于一般的基类‍

面向对象思考

共 1779字,需浏览 4分钟

 ·

2020-02-11 23:24

c54e35415af2f50d0cf1d411d1e43534.webp

C.137: Use virtual bases to avoid overly general base classes

C.137: 使用虚基类避免过于一般的基类‍



Reason(原因)







Allow separation of shared data and interface. To avoid all shared data to being put into an ultimate base class.

允许共享数据和接口的分离。避免将所有的共享数据放进一个终极基类中。


Example(示例)







struct Interface {
    virtual void f();
    virtual int g();
    // ... no data here ...
};

class Utility {  // with data
    void utility1();
    virtual void utility2();    // customization point
public:
    int x;
    int y;
};

class Derive1 : public Interface, virtual protected Utility {
    // override Interface functions
    // Maybe override Utility virtual functions
    // ...
};

class Derive2 : public Interface, virtual protected Utility {
    // override Interface functions
    // Maybe override Utility virtual functions
    // ...
};

Factoring out Utility makes sense if many derived classes share significant "implementation details."

如果很多派生类之间分享特别有用的共通的"实现细节",从中分离出共通功能就是有意义的。


Note(注意)







Obviously, the example is too "theoretical", but it is hard to find a small realistic example. Interface is the root of an interface hierarchy and Utility is the root of an implementation hierarchy. Here is a slightly more realistic example with an explanation.

很显然,示例过于理论化了,但是找到一个接近现实的小例子太难了。接口是接口体系的起点,而公用程序是实现体系的起点。这里有一个带有说明的,略微更接近实际的例子。

链接:https://www.quora.com/What-are-the-uses-and-advantages-of-virtual-base-class-in-C%2B%2B/answer/Lance-Diduck


Note(注意)







Often, linearization of a hierarchy is a better solution.

通常,线性的继承体系是较好的解决方案。


Enforcement(实施建议)







Flag mixed interface and implementation hierarchies.

提示接口继承和实现继承体系混合的情况。


原文链接






https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c137-use-virtual-bases-to-avoid-overly-general-base-classes




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

关注【面向对象思考】轻松学习每一天!

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

浏览 17
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报