开发者

Constructor initialising an array of subobjects?

Say I have several objects within 开发者_StackOverflow中文版a class, each of which needs constructing with a different value. I can write something like this:

class b
{
public:
  b(int num)
    {
    // 1 for a.b1, and 2 for a.b2
    }
};

class a
{
public:
  b b1;
  b b2;
  a() : b1(1), b2(2)
    {
    }
};

However, is it possible to do the same thing if those multiple objects are stored in an array?

My first attempt at it doesn't compile:

class a
{
public:
  b bb[2];
  a() : bb[0](1), bb[1](2)
    {
    }
};


You cannot do this directly; you need to initialize the array elements in the body of the constructor.

The elements of the array are default constructed before the body of the constructor is entered. Since your example class b is not default constructible (i.e., it has no constructor that can be called with zero parameters), you can't have an array of b as a member variable.

You can have an array of a type that is not default constructible in other contexts, when you can explicitly initialize the array.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜