Initializing class inside class

2019-09-13 20:45发布

问题:

I am new to C++, and my question might be trivial, but I wasn't able to find a solution.

I have two classes, S and L. S looks like this:

class S
{
private:
    int m_x;

public:
    S(int x) : m_x(x)
    {
    }

    int m_y = 2*m_x;   // some random action in S
};

Now I have a second class L, where I want to initialize an S-object:

class L
{
private:
    S s(10);   // 10 is just some random value
    int m_y;
public:
    L(int y): m_y(y)
    {
    }

// ignore the rest for now.
};

This produces an error error: expected identifier before numeric constant at the line of initialization of s(10).

I don't understand why I can't do that. How could I fix this? What if I wanted to initialize the object S s(m_y) instead?

回答1:

You could use member initializer list, as you did for m_y:

L(int y): s(10), m_y(y)
{
}

Or use default initializer list from C++11, but note it's only supported for brace or equals initializer, not including the parenthesis one.

class L
{
private:
    S s{10};   // or S s = S(10);
    int m_y;
public:
    L(int y): m_y(y) // s is initialized via default initializer list
                     // m_y is initialized via member initializer list
    {
    }
};


回答2:

You are using a >c++11 compiler and using in class non static member initialization as demonstrate with the line int m_y = 2*m_x;. To use the same initialization mechanism with constructable object, you have to use the uniform initialization syntax, using braces :

class L
{
private:
    S s{10};   // use braces
    int m_y;
public:
    L(int y): m_y(y)
    {
    }

// ignore the rest for now.
};