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-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
