2009-03-05 74 views
5

有什么方法可以延迟定义数组的大小,直到类方法或构造函数?在C++中的类定义中延迟数组大小?

我在想什么的可能会是这个样子,它(当然)不工作:

class Test 
{ 
    private: 
    int _array[][]; 

    public: 
    Test::Test(int width, int height); 
}; 

Test::Test(int width, int height) 
{ 
    _array[width][height]; 
} 

回答

8

Daniel在谈论的是当你的Test(width,height)方法被调用时,你将需要为你的数组动态分配内存。

您将宣布你的二维像这样(整数假设数组):

int ** _array; 

然后在您的测试方法,你需要首先分配指针数组,然后每个指针分配的整数阵列:

_array = new *int [height]; 
for (int i = 0; i < height; i++) 
{ 
    _array [i] = new int[width]; 
} 

然后当对象被释放时,您将需要显式删除您分配的内存。

for (int i = 0; i < height; i++) 
{ 
    delete [] _array[i]; 
    _array [i] = NULL; 
} 
delete [] _array; 
_array = NULL; 
+0

可以添加指针数组分配:_array =新INT [身高]。 Upvoted虽然提供了源! – 2009-03-05 06:25:56

+0

糟糕。谢谢丹尼尔。我忘了补充一点:)。干杯。 – RedBlueThing 2009-03-05 06:28:20

2

我觉得是时候让你来查找新/ delete操作符。

看到,因为这是一个多维数组,你会通过调用“新”,你去(并再次,不要忘记:删除)有循环。

虽然我相信很多人会建议使用宽度*高度元素的一维数组。

8

载体是

class Test 
{ 
    private: 
    vector<vector<int> > _array; 

    public: 
    Test(int width, int height) : 
     _array(width,vector<int>(height,0)) 
    { 
    } 
}; 
1

(几个月后)你最好的朋友一个可以使用的模板,像这样:

// array2.c 
// http://www.boost.org/doc/libs/1_39_0/libs/multi_array/doc/user.html 
// is professional, this just shows the principle 

#include <assert.h> 

template<int M, int N> 
class Array2 { 
public: 
    int a[M][N]; // vla, var-len array, on the stack -- works in gcc, C99, but not all 

    int* operator[] (int j) 
    { 
     assert(0 <= j && j < M); 
     return a[j]; 
    } 

}; 

int main(int argc, char* argv[]) 
{ 
    Array2<10, 20> a; 
    for(int j = 0; j < 10; j ++) 
    for(int k = 0; k < 20; k ++) 
     a[j][k] = 0; 

    int* failassert = a[10]; 

}