创建一个动态2D数组来存储类对象
Creating a dynamic 2D array to store class objects
所以我有一个名为单元格的类,我需要创建一个新的单元格,然后将其放入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];
}
相关文章:
- 多维数组存储三种不同的数据类型?
- C++将原始字符数组存储在元组中
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 如何将JSON数组存储在Arduino程序中
- 如何在AVR(例如:ATMega)或Arduino微控制器上制作2D PROGMEM阵列的1D PROGMEM数组(存储
- 使用 char 数组存储数据
- 使用平面数组存储的元组容器
- 数组 存储并要求用户搜索它
- 将值从一个 char 数组存储到另一个 char 数组
- 如何使字符串数组存储在向量中
- 将构造的静态数组存储在多个文件中的内存中
- 将整数数组存储在堆上并通过指针访问它们
- c++声明一个数据类型的字节数组,该数组存储在字符串中
- 使用指针数组存储阶乘计算的所有中间结果
- 使用异构数组存储不同的子类
- 读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件C++中
- 尝试将复杂数组存储到类 c++ 中
- 在字节数组存储中嵌入 int/string