[英]How to initialize a multi-dimensional array in a C++ constructor
我有一個 class 包含一些多維 arrays。 我正在嘗試在構造函數中初始化這些 arrays,但我無法弄清楚如何去做。 該數組始終具有固定大小。 這是我到目前為止所擁有的:
class foo {
private:
int* matrix; //a 10x10 array
public:
foo();
foo:foo() {
matrix = new int[10][10]; //throws error
}
我得到的錯誤是:
cannot convert `int (*)[10]' to `int*' in assignment
我怎樣才能做到這一點? 最好,我希望數組默認為全 0 的 10x10 數組。
#include <memory.h>
class foo
{
public:
foo()
{
memset(&matrix, 100*sizeof(int), 0);
}
private:
int matrix[10][10];
};
也就是說,如果您沒有將自己綁定到使用指針來執行此操作(否則您可以只將指針傳遞給 memset,而不是對數組的引用)。
做這個:
int **matrix; //note two '**'
//allocation
matrix = new int*[row]; //in your case, row = 10. also note single '*'
for(int i = 0 ; i < row ; ++i)
matrix[i] = new int[col]; //in your case, col = 10
//deallocation
for(int i = 0 ; i < row ; ++i)
delete [] matrix[i];
delete matrix;
建議:您可以使用std::vector
代替使用int**
:
std::vector<std::vector<int> > matrix;
//then in the constructor initialization list
foo() : matrix(10, std::vector<int>(10))
{ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is called initialization list
}
如果您遵循這種方法,則無需在代碼中使用new
和delete
。 此外,矩陣的大小為10x10
; 您可以將它們作為matrix[i][j]
訪問,其中0<=i<10
和0<=j<10
; 還要注意, matrix
中的所有元素都用0
初始化。
嘗試這個:
class foo
{
private:
int **matrix;
public:
foo()
{
matrix = new int*[10];
for (size_t i=0; i<10; ++i)
matrix[i] = new int[10];
}
virtual ~foo()
{
for (size_t i=0; i<10; ++i)
delete[] matrix[i];
delete[] matrix;
}
};
在您的編譯器支持 C++0x 統一初始化之前,如果您想在初始化列表中這樣做,恐怕您必須分別初始化數組中的每個條目。
但是,您可以做的是不初始化而是分配給構造函數內的數組(簡單的 for 循環)。
在您的代碼中,您有一個指針,而不是一個數組。 如果您需要為您處理 memory 管理的元素集合,您可能想要使用 std::vector 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.