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++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
