字段具有不完整的类型错误 - 转发声明

时间:2016-01-02 01:15:56

标签: c++

我认为这里只有以下标题:

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 个答案:

答案 0 :(得分:2)

1)在所有头文件中添加防止双重包含的警卫。最简单的方法(大多数编译器都支持):

#pragma once

2)在Player.h dont #include Game.h中打破循环依赖,但只执行Game类的“前向声明”,因为你只需要通过指针使用它:

class Game;

3)同样,在Piece.h dont #include Player.h,但只向前声明类Player:

class Player;

作为一个简单而通用的规则,当您在头文件中看到您引用另一个类但仅通过指针时,请不要包含此其他类的标头,而只是向前声明它。此规则不仅会破坏循环依赖关系,而且甚至可以最小化依赖关系,从而加快编译速度并提高可维护性。