02.11 分离接口继承和实现继承

分离接口继承和实现继承

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

<code>structInterface{
virtualvoidf();
virtualintg();
//...nodatahere...
};

classUtility{//withdata
voidutility1();
virtualvoidutility2();//customizationpoint
public:
intx;
inty;
};

classDerive1:publicInterface,virtualprotectedUtility{
//overrideInterfacefunctions
//MaybeoverrideUtilityvirtualfunctions
//...
};

classDerive2:publicInterface,virtualprotectedUtility{
//overrideInterfacefunctions
//MaybeoverrideUtilityvirtualfunctions

//...
};/<code>

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


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

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


分享到:


相關文章: