私有继承与包含

发布于 2025-01-03 15:00:59 字数 314 浏览 0 评论 0原文

在解释何时必须使用私有继承而不是包含时,文章 说:

“我们需要在另一个基础子对象之前构造使用的对象,或者在另一个基础子对象之后销毁它,如果稍微长一点的对象生命周期很重要,那么除了使用继承之外没有其他方法可以获取它”。

如果您希望子对象 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回首观望 2025-01-10 15:00:59

我相信作者正在谈论基本子对象,而不是直接子对象。也就是说,如果您希望在构造该类的其他基类之前构造该类的某些成员,则可以使用私有继承。在这种情况下,使用私有继承将导致 C++ 在其他基类之前初始化私有继承的基类,前提是您已按正确的顺序从它们继承。例如,如果您要创建类 Derived,需要在 Derived 中创建一个 Subobject 对象,并从 Base 继承,但是您希望 SubobjectBase 之前初始化,您可以这样写

class Derived: private Subobject, public 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 a Subobject object in Derived, and inherit from Base, but you want the Subobject initialized before the Base, you could write

class Derived: private Subobject, public Base {

}

And now the Subobject will be initialized before the Base.

(That said, this is a pretty silly use case!)

Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文