前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c++核心准则C.137: 使用虚基类避免过于一般的基类‍

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

作者头像
面向对象思考
发布2020-03-25 16:43:52
5120
发布2020-03-25 16:43:52
举报

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(示例)

代码语言:javascript
复制
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


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

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

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档