2014-01-16 40 views
0

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

通函包括 - 替換包括儘可能前向聲明。 –

+0

爲什麼'Pieces'需要了解'ChessBoard'? 「Piece」不屬於「ChessBoard」嗎?將'isValidMove'移動到'ChessBoard'。 – bblincoe

+0

我已經做了一個方法isValidMove在Pieces,檢查被調用的Piece是否可以在給定的Board中移動。所以我需要董事會來檢查。 – user2709885

回答

0

這就是所謂的冗餘包容。 當你在兩個類中包含H(棋子和棋盤)時,C++通常會給出奇怪的錯誤。當你開始用C++編程時,這是一個非常常見的錯誤。

首先,我建議你檢查一下你是否真的需要將每個類都包含在其他類中。如果你確實確信,那麼解決這個問題的方法就是選擇其中的一個,並將include包含到cpp中。 然後在h中添加一個類的預先聲明。

例如,如果您選擇棋盤改變:

#include <map> 
#include <string.h> 

class Pieces; 

class ChessBoard 
    { 

在棋盤CPP你有你自己的#include 「Pieces.h」

件H和CPP保持不變。

1

這是由於稱爲循環依賴的原因。 circular dependency

問題是當你的程序開始編譯時(讓我們假設chessboard.h先開始編譯)。
它把指令包括pieces.h所以跳過代碼的其餘部分,並移動到pieces.h
這裏編譯器看到指令包括chessboard.h
但因爲你提供一個頭文件保護它不包括chessboard.h第二次。
它繼續編譯其餘部分代碼片.h
這意味着chessboard.h中的類還沒有被聲明,它會導致錯誤
最好的想法,以避免這是轉發聲明其他類相當比包含一個頭文件。但是您必須注意,您不能創建任何前向聲明類的對象,只能創建指針或引用變量。

前進聲明是指在使用它之前聲明該類的方法。

class ChessBoard; 

class Pieces 
{ 
    ChessBoard *obj; // pointer object 
    ChessBoard &chessBoard; 
相關問題