开发者

Problem with object declaration/initialization as a private member on a different class

Sorry if this has been asked before, I can't seem to find开发者_如何学C 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?


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) {
            ...
        }
};


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.


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) {}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜