字段具有不完整类型错误 - 前向声明

3
我认为这里只有以下标题是相关的:

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中有一个前向声明,但我不确定为什么这是个问题。


不要在player.h中包含game.h,因为它们互相需要。在Player中,您需要Game *,因此可以在class Player之前编写class Game;。然后在class Player { };之后包含game.h。 - Pierre Emmanuel Lallemant
当你有两个相互依赖的类时,如果你不使用指针,比如 Player White,你需要先完整地定义 Player 类。 - Pierre Emmanuel Lallemant
非常感谢。不确定我是否能够理解这些东西! - user3457175
1个回答

3

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

#pragma once

2) 为了打破循环依赖关系,在Player.h中不要#include Game.h,而只需对Game类进行"前向声明",因为你只需要通过指针来使用它:

class Game;

3) 同样地,在 Piece.h 中不要 #include Player.h,只需要前向声明类 Player:

class Player;

一个简单的并且通用的规则是:当你在头文件中引用另一个类,但仅通过指针使用时,不要包含该类的头文件,只需进行前向声明即可。这个规则不仅可以打破循环依赖关系,还可以最小化依赖关系,从而提高编译速度和代码可维护性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接