作为不同类上的私有成员的对象声明/初始化问题

发布于 2024-10-21 22:05:10 字数 464 浏览 4 评论 0原文

抱歉,如果以前有人问过这个问题,我似乎找不到任何东西。我不知道如何搜索这个。

我有这样的事情:

class A {
    private:
        int x;
        int y;
    public:
        A(int, int);
}

class B {
    private:
        A a(3, 4); // Doesn't compile because of this line
    public:
        B();
}

我能想到解决这个问题的唯一方法是使 a 成为指向 A 的指针,然后执行 a = new A(3, 4 );B 的构造函数中。但我不希望 a 成为一个指针。

解决这个问题的正确方法是什么?

Sorry if this has been asked before, I can't seem to find anything. I'm not sure how to search for this.

I have something like this:

class A {
    private:
        int x;
        int y;
    public:
        A(int, int);
}

class B {
    private:
        A a(3, 4); // Doesn't compile because of this line
    public:
        B();
}

The only way I could think to solve this was making a a pointer to A and then do a = new A(3, 4); inside B's constructor. But I don't want a to be a pointer.

What's the correct way to solve this?

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

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

发布评论

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

评论(3

没︽人懂的悲伤 2024-10-28 22:05:10

您可以使用“成员初始化列表”标记 B 的构造函数。而不是:

B::B() {
    ...
}

您这样做:

B::B() : a(3, 4) {
    ...
}

或者如果构造函数是在标头中定义的:

class B {
    private:
        A a;
    public:
        B() : a(3, 4) {
            ...
        }
};

You tag B's constructor with a "member initialization list". Instead of:

B::B() {
    ...
}

You do this:

B::B() : a(3, 4) {
    ...
}

Or if the constructor is defined in the header:

class B {
    private:
        A a;
    public:
        B() : a(3, 4) {
            ...
        }
};
柏林苍穹下 2024-10-28 22:05:10
class B {
    private:
        A a;
    public:
        B() : a(3,4) {}
};

In a wider sense, the solution is to learn C++ by reading a book about it. Yes, that's snarky, but the point of tutorials is that they introduce concepts in a sensible order, and when they tell you about data members they will simultaneously tell you how to initialize them.

一萌ing 2024-10-28 22:05:10

如果您想要使用参数 3 和 4 初始化 Ba,那么您可以在 B 的构造函数中执行此操作,例如,

class B {
    private:
        A a;
    public:
        B(): a(3, 4) {}
}

If what you want is for B.a to be initialized with the arguments 3 and 4, then you do that in B's constructor, e.g.,

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