c ++ 03使用多个参数初始化对象的数组 [英] c++03 Initializing a array of objects with multiple parameters

查看:129
本文介绍了c ++ 03使用多个参数初始化对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但我正在尝试使用参数化构造函数初始化对象数组.例如:

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.

有没有更简单的方法.另外,所有对象的i,j值都是相同的(可通过main()获得),但是 d 应该是随机值,并且与每个对象都不同.

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.

推荐答案

您可以使用std :: generate

You can use std::generate

示例:

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

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

这篇关于c ++ 03使用多个参数初始化对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆