创建一个动态2D数组来存储类对象

Creating a dynamic 2D array to store class objects

本文关键字:数组 存储 对象 2D 动态 一个 创建      更新时间:2023-10-16

所以我有一个名为单元格的类,我需要创建一个新的单元格,然后将其放入2D数组中。我相信问题是我如何创建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 = '#';
                ^

更改行

Cell* board = new Cell[h]

to

Cell** board = new Cell*[h]

基本上您要创建一个2D数组,因此您需要创建和数组Cell指针(new Cell*[h])。然后,对于每个细胞指针,您都希望为每个单个单元分配内存。这是在循环中完成的:

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