我想做一個象棋遊戲。我做了兩個頭文件和它們的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