2016-10-10 183 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});