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

匆匆过客 提交于 2019-12-11 00:19:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!