2016-10-10 184 views
0

快速的問題:C++數組構造函數的參數

如果我有一類叫什麼(無所謂),然後讓我們說我像

int a[2]; 
int b[2]; 

public: 

classname(int a[], int b[]); // Constructor 

在我的課(private成員)我想要一個默認的構造函數(必須)來初始化這些點(a和b)。我想在我的主一樣適用的東西:

int main(){ 

classname x({4,5},{1,10}); 

return 0; 
} 

但我得到的是一個錯誤,指出沒有匹配的構造函數。我也嘗試過在構造函數中使用*而不是[],但它似乎無法工作。我只是想念一些東西。我試圖用基本的C++保持簡單。

謝謝。

+0

對不起,只是在發佈時錯過了 – Miguel

+1

我建議你看看'std :: array'。 – NathanOliver

回答

0

的問題是,僅使用{ }數組不能初始化。 他們可以這樣做時被初始化,

int arr[4] = {0, 1, 2, 3}; 

但只因爲你「告訴」 C++數組有其大小。如果您嘗試在構造函數中執行此操作,它將會失敗,因爲它不知道數組的大小。 你想達到什麼可以通過使用標準容器來完成。正如@NathanOliver建議的那樣,你可以使用std::array,但這樣你必須指定一個固定大小的數組。

#include <array> 

class Test 
{ 
public: 
    Test(std::array<int, 4> a) {}; 
}; 

// now you can call it 
Test obj1({0, 1, 2, 4}); 

但是,如果你想讓它更靈活,不會綁定到固定數組大小,我建議使用std::vector代替。

#include <vector> 

class Test 
{ 
public: 
    Test(std::vector<int> a) {}; 
}; 

// now you can call it with as many objects as you want 
Test obj1({0, 1, 2, 4, 5, 6, 7, 8});