Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize an array of objects whose constructor require two or more arguments? [duplicate]

Tags:

c++

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?

like image 667
Yishu Fang Avatar asked Mar 11 '12 16:03

Yishu Fang


Video Answer


2 Answers

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.

like image 98
Kerrek SB Avatar answered Oct 31 '22 12:10

Kerrek SB


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).

like image 26
Dietmar Kühl Avatar answered Oct 31 '22 11:10

Dietmar Kühl