我想做一个象棋游戏。我做了两个头文件和它们的cpp文件:Pieces.h和ChessBoard.h。我已经在ChessBoard.h中包含了Pieces.h,它的编译正常。但我想要一个需要ChessBoard作为参数的Pieces中的方法。所以当我尝试在ChecesBoard.h中包含Pieces.h时,我会遇到所有奇怪的错误。有人可以请指导我如何将ChessBoard.h包含在Pieces.h中?当我尝试在C++中包含头文件时,为什么会出错?
Pieces.h:
#ifndef PIECES_H
#define PIECES_H
#include <string>
#include "ChessBoard.h"
using namespace std;
class Pieces{
protected:
bool IsWhite;
string name;
public:
Pieces();
~Pieces();
// needs to be overwritten by every sub-class
virtual bool isValidMove(string initial,string final, ChessBoard& chessBoard) = 0;
bool isWhite();
void setIsWhite(bool IsWhite);
string getName();
};
#endif
ChessBoard.h:
#ifndef CHESSBOARD_H
#define CHESSBOARD_H
#include "Pieces.h"
#include <map>
#include <string.h>
class ChessBoard
{
// board is a pointer to a 2 dimensional array representing board.
// board[rank][file]
// file : 0 b 7 (a b h)
std::map<std::string,Pieces*> board;
std::map<std::string,Pieces*>::iterator boardIterator;
public:
ChessBoard();
~ChessBoard();
void resetBoard();
void submitMove(const char* fromSquare, const char* toSquare);
Pieces *getPiece(string fromSquare);
void checkValidColor(Pieces* tempPiece); // to check if the right player is making the move
};
#endif
错误:
ChessBoard.h:26: error: ‘Pieces’ was not declared in this scope
ChessBoard.h:26: error: template argument 2 is invalid
ChessBoard.h:26: error: template argument 4 is invalid
ChessBoard.h:27: error: expected ‘;’ before ‘boardIterator’
ChessBoard.h:54: error: ISO C++ forbids declaration of ‘Pieces’ with no type
ChessBoard.h:54: error: expected ‘;’ before ‘*’ token
ChessBoard.h:55: error: ‘Pieces’ has not been declared
通函包括 - 替换包括尽可能前向声明。 –
为什么'Pieces'需要了解'ChessBoard'? “Piece”不属于“ChessBoard”吗?将'isValidMove'移动到'ChessBoard'。 – bblincoe
我已经做了一个方法isValidMove在Pieces,检查被调用的Piece是否可以在给定的Board中移动。所以我需要董事会来检查。 – user2709885