问题描述
我正在尝试创建一个国际象棋引擎,所以我创建了一个 Board 类(只显示 h 文件,因为实现非常简单):
class Board {
private:
Piece* board[SIZE][SIZE];
bool turn;
public:
Board();
Piece* getBoard() const;
void printBoard() const;
};
这个想法是制作一个充满不同部分的二维数组。 显然,我还创建了一个 Piece 类(所有其他部分的父类):
class Piece {
protected:
bool color;
int PosX;
int PosY;
public:
Piece(const bool c,const int x,const int y);
~Piece();
virtual int tryMove(int toX,int toY,Board &board) const = 0;
virtual char tochar() const = 0;
}
我创建了一个 EmptyPiece 类来尝试初始化数组,但我不知道如何用这些片段填充数组。
EmptyPiece 的 h 文件:
class EmptyPiece : protected Piece {
public:
EmptyPiece(const bool c,const int y);
char tochar() const;
int tryMove(int toX,Board& board) const;
};
这就是我尝试初始化数组的方式:
Board::Board()
{
turn = true;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = EmptyPiece(0,i,j);
}
}
}
导致错误:
E0413 no suitable conversion function from "EmptyPiece" to "Piece *" exists
解决方法
在以下语句的右侧:
board[i][j] = EmptyPiece(0,i,j);
EmptyPiece(0,j)
创建了一个类型为 EmptyPiece
的临时对象,它也可以转换为类型 Piece
。但是左侧需要一个 Piece*
类型的变量,即一个指向 Piece
对象的指针。通常,您不能将 T
类型的变量分配给另一个 T*
类型的变量。
您可以使用以下版本修复它:
board[i][j] = new EmptyPiece(0,j);
但是您需要记住delete
您new
处理过的对象。