#包括和可能的循环引用

#include and possible cyclical reference

本文关键字:循环 引用 包括      更新时间:2023-10-16

所以我最近的错误开始让我非常糟糕,我已经环顾了互联网,我想出的最好的解决方案是我有一个周期性的#include错误,但我不确定到底是什么导致的。我的include结构如下所示:

Player.h -includes-> Pawn.h -includes-> Piece.h -includes-> Player.h

我的意思是,在我看来,这显然是一个循环包含问题,但我不知道如何克服它。更复杂的是,Pawn类扩展了Piece类,Piece类有一个boost::weak_ptr回到Player类。我的包含看起来像这样的原因是因为PlayerPawn s的vector(和其他Piece s),但Pawn也需要调用一些Player的方法,所以我给了基类Piece一个weak_ptrPlayer

我有什么办法可以设计得更好,这样我就不会有一个循环包含?

你可以使用前向声明来解决这个问题;事实上,在大多数情况下,你应该更喜欢它们而不是头文件。

当头文件不需要知道任何的另一个类的实现细节时,你可以为它使用前向声明,而不是包括整个类定义。这基本上告诉编译器'有一个类有这个名字',但没有其他。

// This is a forward declaration. It tells the compiler that there is a 
// class named Player, but it doesn't know the size of Player or what functions
// it has.
class Player; 
struct Piece {
   // This is just a pointer to player. It doesn't need to know any details about
   // Player, it just needs to know that Player is a valid type.
   boost::weak_ptr<Player> player;
};

作为一般规则,如果文件只传递指向某个类型的指针或引用,则应该前向声明该类型。但是,如果它试图实际使用该类型的对象,则会导致编译器错误。在这种情况下,您需要包含适当的标题。

在大多数情况下,您需要在源文件中包含任何前向声明类的头文件,这样您就可以实际使用指向的对象。

在你所有的头文件中使用头保护符,看起来像这样:

#ifndef PLAYER_H
#define PLAYER_H
//contents of your header file go here
#endif

将include(如果可能的话)移到.cpp文件中。如果您仍然有循环,那么将最常见的内容提取到一个单独的文件中。在您的情况下,Piece.h包含Player.h似乎有问题(这里只是猜测)。