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


覺得本文有幫助?請分享給更多人。

面向對象開發,面向對象思考!


分享到:


相關文章: