您好,如果有人可以建议如何正确执行此操作。基本上,我试图制作一个名为Board的类变量,该类变量中包含ChessPiece实例的二维数组。
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
class ChessPiece
{
public:
char ToChar() { return '#'; };
};
class ChessBoard
{
int Size; //This means board is 8x8.
ChessPiece ** Board;
public:
ChessBoard();
int GetSize() { return Size; };
void PlotBoard();
};
ChessBoard::ChessBoard() {
Size = 8;
ChessPiece newBoard[Size][Size];
Board = newBoard; //Problem here!!! How do I make Board an 8x8 array of ChessPiece?
}
void ChessBoard::PlotBoard() {
int x, y;
for (x = 0; x < Size; x++) {
for (y = 0; y < Size; y++)
printf("%c", Board[x][y].ToChar());
}
}
int main()
{
// ChessBoard board;
// printf("%d", board.GetSize());
// board.PlotBoard();
ChessBoard * a = new ChessBoard();
return 0;
}
我确实在这里想念的很基本的东西,但是我似乎无法弄清楚。
谢谢!
最佳答案
确实没有理由在您的方案中使用原始指针。我建议将电路板作为一维std::vector
持有,并在迭代电路板时仅对行/列使用乘法。
class ChessBoard
{
public:
ChessBoard(size_t row_count) : Size(row_count), Board(row_count * row_count)
{
}
void PlotBoard()
{
for(size_t row = 0; row < Size; ++row)
{
for(size_t col = 0; col < Size; ++col)
printf("%c", Board[(row * Size) + col].ToChar());
}
}
}
private:
size_t Size;
std::vector<ChessPiece> Board;
};