簡體   English   中英

嘗試在C ++中包含頭文件時為什么會出現錯誤?

[英]Why do I get errors when I try to include a header file in C++?

我正在嘗試下棋游戲。 我制作了兩個頭文件及其cpp文件:Pieces.h和ChessBoard.h。 我在ChessBoard.h中包含了Pieces.h,並且編譯良好。 但是我想在Pieces中有一個需要ChessBoard作為參數的方法。 因此,當我嘗試將ChessBoard.h包含在Pieces.h中時,我會得到所有奇怪的錯誤。 有人可以指導我如何將ChessBoard.h包含在Pieces.h中嗎?

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

這是由於所謂的循環依賴引起的。 循環依賴

問題在於,當程序開始編譯時(讓我們假設Chessboard.h首先開始編譯)。
它看到指令包含了pieces.h,因此它跳過了其余代碼,並移至pieces.h
在這里,編譯器看到指令包括chessboard.h
但是由於您包含了標題保護,因此第二次不包含Chessboard.h。
它繼續在pieces.h中編譯其余代碼。
這意味着Chessboard.h中的類尚未被聲明,並且會導致錯誤
避免這種情況的最佳方法是向前聲明另一個類,而不是包含頭文件。 但是必須注意,您不能創建前向聲明類的任何對象,而只能創建一個指針或一個引用變量。

前向聲明意味着在使用類之前對其進行聲明。

class ChessBoard;

class Pieces
{
  ChessBoard *obj;  // pointer object
  ChessBoard &chessBoard;

這稱為冗余包含。 當您在兩個類(片段和棋盤)中同時包含H時,C ++通常會給出奇怪的錯誤。 當您開始使用C ++編程時,這是一個非常常見的錯誤。

首先,我建議您檢查是否真的需要將每個類都包含在另一個類中。 如果您對此確實有把握,那么解決該問題的方法是選擇其中一個並將包含內容移至cpp。 然后在h中添加該類的預聲明。

例如,如果選擇ChessBoard進行更改:

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

class Pieces;

class ChessBoard
  {

在ChessBoard cpp中,您將擁有#include“ Pieces.h”

片段h和cpp保持不變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM