如何为抽象类创建二维数组

时间:2014-12-27 17:00:46

标签: c++ arrays inheritance abstract-class

我试图建立一个国际象棋棋盘。我得到了这个

class ChessPiece 
{
public:
    ChessPiece();
    virtual ~ChessPiece();
    virtual bool movePiece() = 0;
};

和这个班级

class Pawn: public ChessPiece
{
public:
    Pawn();
    virtual ~Pawn();
    bool movePiece();
};

在我的主要人物中我试图创建一个二维ChessPiece数组,但因为它的抽象,它给了我一些问题。

我试过这个

ChessPiece** board = new ChessPiece[8][8];

ChessPiece*** board = new ChessPiece*[8];

但它似乎不起作用.. 任何帮助将不胜感激 谢谢!

1 个答案:

答案 0 :(得分:4)

您的董事会必须指向ChessPiece,每个部分单独分配。董事会总是8x8,所以没有理由用new分配它。代替:

ChessPiece * board[8][8];

然后像:

for (int i = 0; i < 8; ++i) {
    board[1][i] = new Pawn();
}
board[0][0] = new Rook();
board[0][1] = new Knight(); 
// etc...

编辑:使用每种作品类型的固定大小数组删除了一个实现,因为它可以将棋子升级为其他作品类型。)

当然,您可以以不同方式排列数据。您应该将所有游戏数据分组到ChessGame类或结构中。您可以编写一个仅包含一个播放器片段的PlayerPieces课程,然后将其中两个放入ChessGame。有很多可能性 - 最终取决于你自己的风格和偏好。

相关问题