C++继承类与创建成员的类

发布于 2025-02-06 00:55:07 字数 766 浏览 2 评论 0原文

假设我有一个具有多种方法的课程。 我喜欢分为多个类。 我可以继承该类,还是可以与该类创建成员? 哪一个更有效和可用?

假设我有以下课程

class ClassRoom {
    vector<int> BoysIds;
    vector<int> GirlsIds;
public:
    void RegisterBoy(int i);
    void RegisterGirl(int i);
    int GetTotalBoys();
    int GetTotalGirls();
};

,并且我已经分为多个类,例如下面的

class Boys {
    vector<int> BoysIds;
public:
    void RegisterBoy(int i);
    int GetTotalBoys();
};

class Girls {
    vector<int> GirlsIds;
public:
void RegisterGirl(int i);
int GetTotalGirls();
};

继承班级更有效?

class ClassRoom : public Boys, public Girls {
};

创建成员更有效吗?

class ClassRoom {
public:
    Boys m_boys;
    Girls m_girls;
};

Let say I have a class with multiple methods.
I like to separate into multiple classes.
Can I inherit that classes or can I create member with that classes?
Which one is more efficient and usable?

Let's say i have this below class

class ClassRoom {
    vector<int> BoysIds;
    vector<int> GirlsIds;
public:
    void RegisterBoy(int i);
    void RegisterGirl(int i);
    int GetTotalBoys();
    int GetTotalGirls();
};

And i have separated into multiple classes like below

class Boys {
    vector<int> BoysIds;
public:
    void RegisterBoy(int i);
    int GetTotalBoys();
};

class Girls {
    vector<int> GirlsIds;
public:
void RegisterGirl(int i);
int GetTotalGirls();
};

inheriting a class is more efficient?

class ClassRoom : public Boys, public Girls {
};

creating a member is more efficient?

class ClassRoom {
public:
    Boys m_boys;
    Girls m_girls;
};

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

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

发布评论

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

评论(1

能怎样 2025-02-13 00:55:08

多个继承和成员都是有效的。但是,在这里使用会员,而不是多重继承可能是更好的样式,除非您有一个充分的理由。仅在没有任何其他理由的情况下将班级分配,可能不是使用多重继承的充分理由。

通常,除非有充分的理由需要使用它,否则应避免多个继承。

此外,近几十年来,拥有成员(您的类“ has-a” 男孩和a girls)是继承的(您的类“ IS-A” Boys女孩),除非有充分的理由这样做。

您仍然可以在不使用多个继承的情况下将成员分为单独的类。但是,如果您想在单独的类中定义公共方法,则需要手动转发它们。

Both multiple inheritance and members are efficient. However, it is probably better style to use members here, not multiple inheritance, unless you have a really good reason for it. Just splitting the class up, without any other justification, is probably not a good enough reason to use multiple inheritance.

As a general rule, multiple inheritance should be avoided unless there is a good reason why you need to use it.

Also, in recent decades, having members (your class "has-a" Boys and a Girls) is preferred to inheritance (your class "is-a" Boys and a Girls) unless there is a good reason to do otherwise.

You can still make your members separate classes, without using multiple inheritance. However, if you want to define your public methods in the separate classes, you will need to forward them manually.

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