简体   繁体   中英

c++03 Initializing a array of objects with multiple parameters

This might be a simple question but I am trying to initialize an array of objects using a parameterized constructor. For example:

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

void A::A(int i, int j){
    d = rand()
    b = 2*i;
    c = 3*j;
}

void main(){
    A a[50]; /*Initialize the 50 objects using the constructor*/
}

I have already tried with vector initialization as mentioned in this link however, since there are 2 parameters, this does not work.

Also, as mentioned in this link , it is not possible and tedious to manually enter 50 initialization values.

Is there a easier way. Also, i,j values are the same for all objects (available through main()) but d should be random value and differs from each object.

You can use std::generate

Example:

A generator(){ return A(1,2); }

std::generate( a, a + (sizeof(a) / sizeof(a[0])), generator );

Why not supply default arguments to your two-argument constructor?

A (int i = 0, int j = 0);

Then it will stand in for the default constructor, and A a[50]; will use it automatically 50 times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM