gpt4 book ai didi

c++ - #include 和可能的循环引用

转载 作者:太空狗 更新时间:2023-10-29 21:06:07 25 4
gpt4 key购买 nike

所以我最近的错误开始让我非常烦恼,我环顾了互联网,我想出的最好的解决方案是我有一个周期性的 #include 错误,但是我我不确定到底是什么原因造成的。我的包含结构如下所示:

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

我的意思是,在我看来这是一个循环包含问题,但我不知道如何克服它。使事情复杂化的是,Pawn 类扩展了 Piece,并且 Piece 有一个返回 boost::weak_ptr播放器。我的包含看起来像这样的原因是因为 Player 有一个 vectorPawn(和其他 Piece)但是Pawn还需要调用一些Player的方法,所以我给基类Piece一个weak_ptrPlayer

有什么方法可以更好地设计它,从而避免循环包含?

最佳答案

您可以通过使用前向声明来解决这个问题;事实上,在大多数情况下,您应该更喜欢它们而不是包含 header 。

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

// 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;
};

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

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

关于c++ - #include 和可能的循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8252910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com