两个派生类之间的聚合

发布于 2025-02-12 18:04:20 字数 272 浏览 1 评论 0原文

可以在一个基类的两个派生类之间存在聚合关系类型(例如,一个类包含另一个类的向量)吗?

它可以在C ++中实施吗?如果是这样,它是否被认为是一种好实践,并且不违反逻辑吗?

图片中的示例: “类图”

Can there be an aggregation relationship type between two derived classes of one base class (for example, one class contains vector of another)?

Can it be implemented in C++ and if so, is it considered a good practice and does not violate logic or not?

Example in picture: class diagram

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

以为你会在 2025-02-19 18:04:20

简短的答案是肯定的,您的班级图显示了您何时这样做的示例。除了按钮是实际的“物理”项目,并且具有唯一的身份,您不能仅在数据结构中复制它们,您可能会使用这些按钮使用指示,在C ++中使用这些指针。智能指针:

std::vector <std::unique_ptr<Button> > buttons;

使用指针还允许myWindow包含其他myWindow,而无需您遇到有关不完整类型的编译器错误。

Short answer is yes, and your class diagram shows an example of when you'd do this. Except buttons are actual, "physical" items on screen, and have unique identity, you can't just copy them in a data structure, you would probably use pointers to these buttons, in C++ like this using smart pointer:

std::vector <std::unique_ptr<Button> > buttons;

Using pointers also allows for example MyWindow contain other MyWindow without you getting compiler errors about incomplete type.

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