有什麼方法可以延遲定義數組的大小,直到類方法或構造函數?在C++中的類定義中延遲數組大小?
我在想什麼的可能會是這個樣子,它(當然)不工作:
class Test
{
private:
int _array[][];
public:
Test::Test(int width, int height);
};
Test::Test(int width, int height)
{
_array[width][height];
}
有什麼方法可以延遲定義數組的大小,直到類方法或構造函數?在C++中的類定義中延遲數組大小?
我在想什麼的可能會是這個樣子,它(當然)不工作:
class Test
{
private:
int _array[][];
public:
Test::Test(int width, int height);
};
Test::Test(int width, int height)
{
_array[width][height];
}
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;
我覺得是時候讓你來查找新/ delete操作符。
看到,因爲這是一個多維數組,你會通過調用「新」,你去(並再次,不要忘記:刪除)有循環。
雖然我相信很多人會建議使用寬度*高度元素的一維數組。
載體是
class Test
{
private:
vector<vector<int> > _array;
public:
Test(int width, int height) :
_array(width,vector<int>(height,0))
{
}
};
(幾個月後)你最好的朋友一個可以使用的模板,像這樣:
// 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];
}
可以添加指針數組分配:_array =新INT [身高]。 Upvoted雖然提供了源! – 2009-03-05 06:25:56
糟糕。謝謝丹尼爾。我忘了補充一點:)。乾杯。 – RedBlueThing 2009-03-05 06:28:20