创建动态2D数组以存储类对象

时间:2017-12-06 02:35:35

标签: c++ arrays class

所以我有一个名为Cell的类,我需要创建一个新的Cell并将其放入一个二维数组中。我相信问题是我如何创建2D数组。我已经查看了动态数组的工作原理,但我仍然无法找到问题所在。下面是我的一些代码和我得到的前几个错误

    Cell * board = new Cell[h]; //create new board
        for(int i = 0; i < h; i++){
            board[i] = new Cell[w];
            }
        for (int row = 0; row < h; row ++){     //initialize board
            for (int col = 0; col < w; col++){
                board[row][col] = new Cell; 
                board[row][col]->status = '#';
                board[row][col]->isCovered = true;
            }
        }

错误:

minesweeper.h: In constructor ‘GameBoard::GameBoard(int, int, int)’:
minesweeper.h:29:17: error: no match for ‘operator=’ (operand types are 
‘Cell’ and ‘Cell*’)
    board[i] = new Cell[w];
             ^
minesweeper.h:29:17: note: candidate is:
minesweeper.h:4:8: note: Cell& Cell::operator=(const Cell&)
 struct Cell
    ^
minesweeper.h:4:8: note:   no known conversion for argument 1 from ‘Cell*’ 
to ‘const Cell&’
minesweeper.h:33:16: error: no match for ‘operator[]’ (operand types are 
‘Cell’ and ‘int’)
      board[row][col] = new Cell; 
            ^
minesweeper.h:34:16: error: no match for ‘operator[]’ (operand types are 
‘Cell’ and ‘int’)
      board[row][col]->status = '#';
                ^

1 个答案:

答案 0 :(得分:1)

更改行

Cell* board = new Cell[h]

Cell** board = new Cell*[h]

基本上你想要创建一个二维数组,所以你需要创建Cell指针数组(new Cell*[h])。然后,对于每个Cell指针,您希望为每个单独的Cell分配内存。这是在循环中完成的:

for(int i = 0; i < h; i++){
    board[i] = new Cell[w];
}