2011-01-20 52 views
0

我試圖將程序轉換爲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

直到新版本的C++出來。但是你應該使用`std :: vector`,而不是`new []`。另外,通過將固定大小的數組更改爲動態數組,可以獲得哪些好處? – GManNickG 2011-01-20 23:12:57

+0

我*仍*無法理解如何不可能有一個簡單的本地對象的數組沒有一個默認的構造函數在舊的C++ ...有沒有他們,就像在C++ 03時忘記它,或者是什麼? – Kos 2011-01-20 23:17:27

回答

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 d吧。)

2

如果您使用std ::向量可以使用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; 

在另一方面,你應該考慮使用固定大小的數組如果是小和大小不變。