繁体   English   中英

制作子元素的二维数组

[英]Making a 2D array of children elements

我正在尝试创建一个国际象棋引擎,所以我制作了一个 Board class(只显示 h 文件,因为实现非常简单):

class Board {
private:
    Piece* board[SIZE][SIZE];
    bool turn;
public:
    Board();
    Piece* getBoard() const;
    void printBoard() const;
};

这个想法是制作一个充满不同部分的二维数组。 显然,我也制作了一块 class (所有其他部分的父 class):

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 class 来尝试初始化数组,但我只是不知道如何用这些碎片填充数组。

EmptyPiece 的 h 文件:

class EmptyPiece : protected Piece {
public:
    EmptyPiece(const bool c, const int x, const int y);
    char toChar() const;
    int tryMove(int toX, int toY, 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, i, j)创建了一个临时的 object 类型为EmptyPiece ,它也可以转换为类型Piece 但是左侧需要一个Piece*类型的变量,即指向Piece object 的指针。 通常,您不能将T类型的变量分配给T*类型的另一个变量。

您可以使用以下版本修复它:

board[i][j] = new EmptyPiece(0, i, j);

但是你需要记住deletenew ed 的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM