#包括和可能的循环引用
#include and possible cyclical reference
所以我最近的错误开始让我非常糟糕,我已经环顾了互联网,我想出的最好的解决方案是我有一个周期性的#include
错误,但我不确定到底是什么导致的。我的include结构如下所示:
Player.h -includes-> Pawn.h -includes-> Piece.h -includes-> Player.h
我的意思是,在我看来,这显然是一个循环包含问题,但我不知道如何克服它。更复杂的是,Pawn
类扩展了Piece
类,Piece
类有一个boost::weak_ptr
回到Player
类。我的包含看起来像这样的原因是因为Player
有Pawn
s的vector
(和其他Piece
s),但Pawn
也需要调用一些Player
的方法,所以我给了基类Piece一个weak_ptr
到Player
。
我有什么办法可以设计得更好,这样我就不会有一个循环包含?
你可以使用前向声明来解决这个问题;事实上,在大多数情况下,你应该更喜欢它们而不是头文件。
当头文件不需要知道任何的另一个类的实现细节时,你可以为它使用前向声明,而不是包括整个类定义。这基本上告诉编译器'有一个类有这个名字',但没有其他。
// 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似乎有问题(这里只是猜测)。
相关文章:
- 打破循环引用在C++中更优雅
- 如何编译使用循环引用的代码?
- 关于C++中引用计数和循环引用的概念
- CBasePin 递增对拥有过滤器的引用.循环引用?
- 使用带有循环引用的weak_ptr
- 如何避免成员回调和shared_ptr循环引用?
- std :: make_shared(),std :: feek_ptr和循环引用
- 由于具有循环引用的类中的unique_ptr或向量而导致核心转储
- 我的内存泄漏是由循环引用引起的吗?
- C++:外部对象循环引用
- 使用 std::weak_ptr 和别名构造函数中断循环引用:声音或有问题
- #ifndef是否可以防止循环引用编译器错误
- shared_ptr和循环引用
- boost::序列化和循环引用反序列化
- 两个类之间的循环引用
- 循环引用的问题
- C++11, shared_ptr.reset() 和循环引用
- 如何初始化 const 循环引用成员
- C++中两个类对象的循环引用
- 如何使用std::shared_ptr检测或避免循环引用