【问题标题】:C++ Array of interface base classes for chess国际象棋接口基类的C++数组
【发布时间】:2014-02-04 10:52:50
【问题描述】:

我正在兜圈子里寻找错误消息,试图弄清楚如何才能得到我需要的工作。

我正在制作一个国际象棋游戏,其中每个棋子都是一个类,并且有一个名为 Piece 的接口类。

Piece.h

class Piece {
public:
    virtual ~Piece() {};
    /*
     * Verifies the move on a per-piece basis. If the move is valid, make the changes on the board and return true, false otherwise.
     *
     * @param b             Reference to the board
     * @param toLocation    Where to move the piece
     * @return bool         If the move is valid
     */
    virtual bool move(Board &b, std::pair<int, int> toLocation) { return false; }

protected:
    Piece(GameData::Color _c) { c = _c; }
    GameData::Color c;
};

Pawn.h

class Pawn : Piece {
public:
    Pawn(GameData::Color _c);
    virtual ~Pawn();
    bool move(Board &b, std::pair<int, int> toLocation);
};

但我无法让此设置正常工作。

我收到一个错误:

Pawn::Pawn(GameData::Color _c) : c(_c) {
no matching function for call to Piece::Piece()

我将 Piece 的可见性更改为:

class Pawn : public Piece

但是当我没有一个空的构造函数时,我会收到更多错误。

我正在设置它以尝试制作一个 2D 棋子数组来代表棋盘:

board = new Piece**[SIZE];
for(int i = 0; i < SIZE; ++i)
    board[i] = new Piece*[SIZE];
/* Setup initial positions */
board[0][0] = new Rook(GameData::BLACK);

这就是为什么我不能让 move 方法纯粹是虚拟的。因为 new Piece* 调用抱怨它需要实现。

【问题讨论】:

  • Pawn::Pawn(GameData::Color _c) : Piece(_c) {}.
  • 很简单嗯..谢谢哈哈..
  • 无数次重复中的一个:g++ no matching function call error
  • 你应该将方法设为虚拟并找出为什么 new Piece*[SIZE];抱怨,因为它不应该。使特定方法成为纯虚拟方法是正确的做法。

标签: c++ oop inheritance interface


【解决方案1】:

编译器抱怨是因为你的Pawn 构造函数没有指定它的Piece 基础子对象应该如何被初始化。通常不指定这个会导致Piece的默认构造函数被调用,但是Piece没有默认构造函数,因此会报错。

通过明确的方式修复它:

Pawn::Pawn(GameData::Color _c) : Piece(_c) {}

这告诉编译器你想通过调用接受Color的构造函数来初始化基类;该构造函数将负责分配c = _c,因此(给定简化示例)您将得到Pawn::Pawn 的空主体。

顺便说一句,由于您打算使用Piece 不仅作为基类,而且还向外界公开接口,所以Pawn 应该公开派生自Piece

【讨论】:

  • 我还打算建议他们在基类中也将 Move 更改为纯虚拟。由于它返回 false 作为默认行为,因此他们打算将其覆盖,我怀疑他们是否只想拥有一个没有任何功能的“Piece”对象。
【解决方案2】:

您必须通过initialization list 调用Piece 构造函数:

Pawn(GameData::Color _c): Piece(_c) {}

或者创建一个默认构造函数并通过方法初始化值。您的选择。

【讨论】:

    猜你喜欢
    • 2022-06-17
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多