私有继承与包含
在解释何时必须使用私有继承而不是包含时,文章 说:
“我们需要在另一个基础子对象之前构造使用的对象,或者在另一个基础子对象之后销毁它,如果稍微长一点的对象生命周期很重要,那么除了使用继承之外没有其他方法可以获取它”。
如果您希望子对象 A 成为在子对象 B 之前构造并在 B 之后析构,在封闭类中,在 B 之前声明 A 还不够吗?换句话说,为什么在这种情况下我们不能用遏制来达到同样的效果呢?
While explaining when private inheritance must be used, instead of containment, the author of this article says the following :
"We need to construct the used object before, or destroy it after, another base subobject. If the slightly longer object lifetime matters, there's no way to get it other than using inheritance"
If you want subobject A to be constructed before subobject B and destructed after B, wouldn't be enough to declare A before B, in the enclosing class ? In other words, why can't we use containment to achieve the same result in this case ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信作者正在谈论基本子对象,而不是直接子对象。也就是说,如果您希望在构造该类的其他基类之前构造该类的某些成员,则可以使用私有继承。在这种情况下,使用私有继承将导致 C++ 在其他基类之前初始化私有继承的基类,前提是您已按正确的顺序从它们继承。例如,如果您要创建类
Derived
,需要在Derived
中创建一个Subobject
对象,并从Base
继承,但是您希望Subobject
在Base
之前初始化,您可以这样写,现在
Subobject
将在Base
之前初始化代码>.(也就是说,这是一个非常愚蠢的用例!)
希望这会有所帮助!
I believe that the author is talking about base subobjects, not direct subobjects. That is, you would use private inheritance if you wanted some member of the class to be constructed before the class's other base classes would be constructed. In this case, using private inheritance will cause C++ to initialize the privately-inherited base class before other base classes, provided that you've inherited from them in the right order. For example, if you're making class
Derived
, want aSubobject
object inDerived
, and inherit fromBase
, but you want theSubobject
initialized before theBase
, you could writeAnd now the
Subobject
will be initialized before theBase
.(That said, this is a pretty silly use case!)
Hope this helps!