【发布时间】:2015-02-21 18:11:34
【问题描述】:
我正在尝试执行以下操作:
class Test{
private:
int x;
int y;
// Create array[][] here
public:
Test(const int x, const int y){
this->x = x;
this->y = y;
// set: array[x][y] here
}
};
如您所见,我想创建一个二维数组,而边界将在构造函数中给出。 我怎样才能做到这一点?
它适用于通常的数组:
class Test{
private:
int x;
int y;
int *array;
public:
Test(const int x, const int y){
this->array = new int[x]; // works
// this->array = new int[x][y] does not work
this->x = x;
this->y = y;
}
};
【问题讨论】:
-
使用
std::vector<std::vector>代替原始指针 -
可以使用模板吗?如果您忘记添加释放数组的析构函数,您的示例将会泄漏。
-
可能值得考虑使用单个 std::vector 而不是 std:vector<:vector>。此外,根据要求,在初始化列表而不是构造函数的主体中实际创建数组可能是一个好主意:
Test(const unsigned x, const unsigned y) : x_(x), y_(y), buffer_(x*y) {}将立即提供具有默认值的有效数组(与未初始化的值相反)。访问元素的算法应该足够简单。
标签: c++ arrays constructor