【发布时间】:2013-08-13 18:56:47
【问题描述】:
您好,如果有人可以建议如何正确执行此操作。基本上,我正在尝试创建一个名为 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<std::vector<ChessPiece>>,或者更简单的std::vector<ChessPiece>,并使用简单的乘法将索引作为行/列进行跟踪。 -
我会像@Chad 那样做。我自己会使用第二个版本,但这并不重要。
-
程序是否只需要支持标准的 8x8 棋盘,或者您是否也希望能够在 8x8 以外的任意大小的棋盘上玩?如果只需要标准的 8x8,不妨将 Size 设为常量,然后使用简单的 8x8 固定大小二维数组即可。