c++ - 交叉引用和循环依赖。 header 间接包含自身

标签 c++ inheritance header circular-dependency cross-reference

可放置的.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/

相关文章:

c++ - 在 Java EE Web 应用程序中打开 TCP 套接字

C++ 做 OS X 或 Linux header 不同

php - laravel5.3 即时生成下载(.txt)

c# - 实体设计与继承

javascript - 为什么 instanceof 在 Javascript 中为子对象返回 false

复除法

c++ - 从共享缓冲区写入文件丢失数据和程序崩溃而没有 cout

c++ - 模板值特化

c++ - 将静态函数删除器与 std::unique_ptr 一起使用时出错

java - 在继承层次结构中实现健壮的 equals() 和 hashCode() 方法的正确方法是什么?