在构造函数上初始化数组

时间:2011-01-20 23:09:40

标签: c++ arrays oop constructor initialization

我正在尝试将程序转换为OOP。该程序适用于几个数组:

int tipoBilletes[9] = { 500,300,200,100,50,20,10,1,2 };
int cantBilletes[9] = {0};

因此,对于我的转换,我在头文件中声明了这个:

int *tipoBilletes;
int *cantBilletes;

在我写的构造函数中

tipoBilletes = new int[9];
cantBilletes = new int[9];

tipoBilletes[0] = 500;
tipoBilletes[1] = 300;
tipoBilletes[2] = 200;
...

工作正常。

我的问题是,有没有办法像Java一样初始化它?

int[] tipoBilletes = new int[]{ 500,300 };

而不是逐个设置每个元素?

2 个答案:

答案 0 :(得分:4)

不,但你不一定要独立写出每个作业。另一种选择是:

const int TIPO_BILLETES_COUNT = 9;
const int initialData[TIPO_BILLETES_COUNT] = { 500,200,300,100,50,20,10,1,2 };
std::copy(initialData, initialData + TIPO_BILLETES_COUNT, tipoBilletes);

(请注意,您几乎肯定会使用std::vector而不是手动动态分配。虽然std::vector一旦resize,{{1}}的初始化也没有什么不同。)

答案 1 :(得分:2)

如果你使用std :: vector,你可以使用boost::assign

#include <vector>
#include <boost/assign/std/vector.hpp>  
//... 
using namespace boost::assign;
std::vector<int> tipoBilletes;
tipoBilletes += 500, 300, 200, 100, 50, 20, 10, 1, 2;

另一方面,如果它是小且恒定的大小,你应该考虑使用固定大小的数组。

相关问题