[英]How to fix an “field has incomplete type” error when using a forward declaration
[英]field has incomplete type error - forward declaration
我認為只有以下標頭與此相關:
Game.h
#include "Player.h"
class Game
{
private:
Player White;
Player Black;
Board current_board;
};
Player.h:
#include "Game.h"
#include "Piece.h"
class Player
{
private:
Chessend end;
std::string name;
std::vector <Piece> pieces;
Board* board_ptr;
Game* game_ptr;
};
Piece.h:
#include "Player.h"
class Player; //forward declaration
class Piece
{
private:
Chesspiece type;
bool moved, taken;
Player *player;
};
給出以下錯誤
In file included from Player.h:11:0,
from Game.h:1,
from main.cpp:1:
Game.h:20:10: error: field 'White' has incomplete type 'Player'
Player White;
^
In file included from Player.h:9:0,
from Game.h:1,
from main.cpp:1:
Piece.h:7:7: note: forward declaration of 'class Player'
class Player;
我知道Piece.h中有一個前向聲明,但是我不確定為什么會出現問題。
1)在所有頭文件中添加防止雙重包含的保護措施。 最簡單的方法(大多數編譯器支持):
#pragma once
2)要打破循環依賴關系,請在Player.h
不要#include Game.h
,但只能對Game類進行“前向聲明”,因為您只需要通過指針使用它:
class Game;
3)同樣,在Piece.h
不要#include Player.h
,而只能向前聲明類Player:
class Player;
作為一個簡單而通用的規則,當您在頭文件中看到僅通過指針引用另一個類的標題時,請勿包括該另一個類的標題,而僅對其進行前向聲明。 該規則不僅會打破循環依賴關系,而且還會使依賴關系最小化,從而可以加快編譯速度並提高可維護性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.