When to use C++ private inheritance over composition?(何时使用 C++ 私有继承而不是组合?)
问题描述
你能举一个具体的例子,什么时候最好使用私有继承而不是组合?就个人而言,我将使用组合而不是私有继承,但在某些情况下,使用私有继承可能是特定问题的最佳解决方案.阅读 C++ faq,为您提供了一个使用示例私有继承,但我似乎更容易使用组合+策略模式,甚至比私有继承更容易使用公共继承.
Can you give me a concrete example when is preferable to use private inheritance over composition? Personally, I will use composition over private inheritance, but there might be the case that using private inheritance is the best solution for a particular problem. Reading the C++ faq, gives you an example on using private inheritance, but I seems easier to use composition + strategy pattern or even public inheritance than private inheritance.
推荐答案
private 继承通常用于表示implemented-in-terms-of".我看到的主要用途是使用私有多重继承的 mixin 来构建具有来自各种 mixin 父项的适当功能的子对象.这也可以通过组合来完成(我稍微喜欢),但是继承方法确实允许您使用 using 公开公开一些父方法,并且在使用 mixin 方法时允许使用更方便的符号.
private inheritance is typically used to represent "implemented-in-terms-of". The main use I have seen is for mixins using private multiple inheritance to build up a child object with the proper functionality from the various mixin parents. This can also be done with composition (which I slightly prefer) but the inheritance method DOES allow you to use using to expose some parent methods publicly, and allows for a slightly more convenient notation when using the mixin methods.
这篇关于何时使用 C++ 私有继承而不是组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:何时使用 C++ 私有继承而不是组合?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
