use*_*491 2 c++ oop inheritance interface
我正在追逐圈子中的错误消息,试图弄清楚我如何得到我需要的工作.
我正在制作一个国际象棋游戏,每个西洋棋棋子都是一个类,并且有一个名为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;
};
Run Code Online (Sandbox Code Playgroud)
Pawn.h
class Pawn : Piece {
public:
Pawn(GameData::Color _c);
virtual ~Pawn();
bool move(Board &b, std::pair<int, int> toLocation);
};
Run Code Online (Sandbox Code Playgroud)
我不能让这个设置工作.
我收到一个错误:
Pawn::Pawn(GameData::Color _c) : c(_c) {
no matching function for call to Piece::Piece()
Run Code Online (Sandbox Code Playgroud)
我将Piece的可见性更改为:
class Pawn : public Piece
Run Code Online (Sandbox Code Playgroud)
但是我得到了更多的错误,我再没有一个空的构造函数.
我正在设置这个以尝试制作一个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);
Run Code Online (Sandbox Code Playgroud)
这就是为什么我不能使移动方法纯粹虚拟..因为新的Piece*调用抱怨它需要实现.
Pawn(GameData::Color _c): Piece(_c) {}
Run Code Online (Sandbox Code Playgroud)
或者创建一个默认构造函数并通过方法初始化值.你的选择.
编译器抱怨,因为Pawn构造函数没有指定Piece应如何初始化其基础子对象.通常不指定这将导致Piece调用默认构造函数,但Piece没有默认构造函数,因此错误.
通过明确修复它:
Pawn::Pawn(GameData::Color _c) : Piece(_c) {}
Run Code Online (Sandbox Code Playgroud)
这告诉编译器你想通过调用接受a的构造函数初始化base Color; 该构造函数将负责分配c = _c(给定简化示例),您将留下一个空体Pawn::Pawn.
顺便说一下,既然您打算Piece不仅将其用作基类,而且还要将接口暴露给外部世界,那么Pawn应该公开派生Piece.
| 归档时间: |
|
| 查看次数: |
608 次 |
| 最近记录: |