问题
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.
回答1:
You can use std::generate
Example:
A generator(){ return A(1,2); }
std::generate( a, a + (sizeof(a) / sizeof(a[0])), generator );
回答2:
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.
来源:https://stackoverflow.com/questions/39642085/c03-initializing-a-array-of-objects-with-multiple-parameters