2014-01-16 36 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; 
相关问题