可放置的.h
#include "selectable.h"
class placeable : selectable
{
..
};
可选择的.h
#include "game.h"
class selectable
{
..
};
游戏.h
#include "placeable.h"
class game
{
...
class placeable* holding;
...
};
基本上 placeable.h 包含 selectable.h,其中包含 game.h,而 game.h 又包含 placeable.h。
我能想到的唯一解决方案是将 placeable* 放在一个新的 header 中,使其成为静态/全局的,然后将这个新 header 包含在 game.h 和 selectable.h 中。
很抱歉,我在上面的代码中包含了头部保护。我以为这很明显。 由于继承,在这种情况下, header 守卫没有帮助,前向声明也是如此。
最佳答案
仅在您必须
时包含 header优先使用前向声明而不是包括:
您只需要包含类 X
的 header 当且仅当:
- 你有一个类(class)“X”的成员
- 您派生自类“X”
- 您按值传递类“X”的参数。
否则前向声明就足够了。
// -> Don't do this #include "placeable.h"
class placeable; // forward declare
// Fine if you are using a pointer.
class game
{
...
class placeable* holding;
...
};
附言。添加 header 保护。
关于c++ - 交叉引用和循环依赖。 header 间接包含自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8619872/