2017-12-06 11 views
1

私はCellというクラスを持っています。新しいCellを作成して2次元配列に配置する必要があります。問題は、私が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; 
      } 
     } 

エラー得る最初のいくつかのエラー:

Cell** board = new Cell*[h] 

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 = '#'; 
       ^
+0

1Dの代わりに2Dを初期化しました。 –

+0

カスタムクラスの2D配列を試みる前に、 'int'の2D配列を試してください。そうすれば、新しい未知数をたくさん導入する前に、これらの問題を解決することができます。 – Beta

答えて

1

変更ライン

Cell* board = new Cell[h] 

は、基本的にはしたいです2次元配列を作成するためには、creaが必要ですポインタとCellポインタの配列(new Cell*[h])。次に、各セルポインタごとに、個々のセルごとにメモリを割り当てます。これはループで行われます。

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

これは私にエラーを返します: 'minesweeper.cppからインクルードされたファイル:2:0: minesweeper.h:コンストラクタ 'GameBoard :: GameBoard(int、int、int)': minesweeper.h:27:30 :エラー:初期化で 'Cell *'を 'Cell **'に変換できません。 Cell ** board = new Cell [h]; //新しいボードを作成する ' –

+0

これはあなたが正しく変更を加えなかったからです。投稿をもう一度読む。 – sashang

+0

ごめんなさい! (非常に少ない睡眠で実行されます)新しいエラー: 'minesweeper.h:コンストラクタ' GameBoard :: GameBoard(int、int、int) ': minesweeper.h:33:22:エラー:' operator = 'に一致しませんオペランドタイプは 'Cell'と 'Cell *') board [row] [col] = new Cell; ^ ' –

関連する問題