Initialize array in constructor without using default constructor or assignment

后端 未结 4 461
日久生厌
日久生厌 2021-01-13 03:56

Consider:

struct A {

 A (int);

 A (const A &);
};

struct B {

 A foo [2];

 B (const A & x, const A & y)
 : foo {x, y} /* HERE IS THE PROBLEM          


        
4条回答
  •  情书的邮戳
    2021-01-13 04:28

    Unfortunately, there really is no proper, clean way to do this. Consider it something of a language limitation that results from an awkward mixing of C++ constructors and C style arrays. The C++11 standard addresses this issue, but until then you'll have to settle for a workaround.

    Since A has no default constructor, one possible work-around is to have an array of A* pointers, and then loop over the array and initialize each one with new. (Obviously, don't forget to delete each item in the array in B's destructor, or just use smart pointers.)

提交回复
热议问题