本文共 1759 字,大约阅读时间需要 5 分钟。
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 pointpublic: 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
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】
转载地址:https://oothinking.blog.csdn.net/article/details/105349926 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!