11

suggest we have an array of class A's objects, and class A's constructor require two arguments, like this:

class A  
{  
public:  
    A( int i, int j ) {}  
};  

int main()  
{
    const A a[3] = { /*How to initialize*/ };

    return 0;
}

How to initialize that array?

Yishu Fang
  • 9,448
  • 21
  • 65
  • 102

4 Answers4

12

Say:

const A a[3] = { {0,0}, {1,1}, {2,2} };

On older compilers, and assuming A has an accessible copy constructor, you have to say:

const A a[3] = { A(0,0), A(1,1), A(2,2) };

C++ used to be pretty deficient with respect to arrays (certain initializations just were not possible at all), and this got a little better in C++11.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • In the first case, the compiler just issue a warming: 'main.cpp:10:32: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default].' What does "accessible" mean? a public one?, and, thank you. – Yishu Fang Mar 11 '12 at 16:22
  • @UniMouS: On GCC, compile with `-std=c++0x`. Accessible means that you can access it, i.e. it's not private or `=delete`d. – Kerrek SB Mar 11 '12 at 16:25
  • thank you, @Kerrek: and what's the meaning of `=delete` ? – Yishu Fang Mar 11 '12 at 16:46
1

As long as the type has a copy constructior (whether synthesized or explicitly defined) the following works:

A array[] = { A(1, 3), A(3, 4), A(5, 6) };

This work both with C++2003 and C++ 2011. The solution posted by KerrekSB certainly does not work with C++ 2003 but may work withC++ 2011 (I'm not sure if it works there).

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

you can provide a default constructor and initialize your array as normal. After successful initialization, use a loop to reassign values to each member

0

i think it should be like this

const A a[3] = { A(1, 2), A(3, 4), A(5, 6) };

Hamed
  • 2,084
  • 6
  • 22
  • 42