交叉引用和循环依赖。标题包括间接

时间:2011-12-23 19:24:55

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

placeable.h

#include "selectable.h"

class placeable : selectable
{
..
};

selectable.h

#include "game.h"


class selectable
{
..
};

game.h

#include "placeable.h"

class game
{
...
class placeable* holding;
...
};

基本上,placeable.h包括selectable.h,其中包括game.h,其中包括placeable.h。

我能想到的唯一解决方案是将placeable *放在一个新的标题中,使其成为静态/全局,然后在game.h和selectable.h中包含这个新标题。

对不起,我在上面的代码中包含了标题保护。我认为很明显。 在这种情况下,由于继承,标题保护没有帮助,同样的事情与前向声明一致。

5 个答案:

答案 0 :(得分:5)

如果您必须

,则只包含标题

优先使用前向声明,包括:

您只需要包含类X iff:

的标头
  • 您拥有“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;
    ...
};

PS。添加标题保护。

答案 1 :(得分:3)

这意味着您没有正确封装设计的功能。它应该是更高级别包括更低级别,而不是同级别包括同级别。如果游戏是更高级别,那么selectable不应该包含game.h。

答案 2 :(得分:2)

这是一个已解决的问题。它被称为标题守卫。在所有头文件中尝试:

#ifndef __NAMEOFTHEFILE_H__
#define __NAMEOFTHEFILE_H__
// nothing goes above the ifndef above

// everything in the file goes here

// nothing comes after the endif below
#endif

此外,您可以这样做(这称为前向参考):

// game.h

class placeable;

class game { ...
    placeable* p;
};

答案 3 :(得分:0)

有两个问题:

  1. 循环标头依赖项。解决方案 - #ifndef ...
  2. 为未知类型分配空间。解决方案 - 可放置类;
  3. 查看更多here

答案 4 :(得分:-1)

在每个头文件中使用标头保护以避免此问题。通常,您的头文件应该是这样的:

#ifndef PLACEABLE_H
#define PLACEABLE_H

//
// Class definitions and function declarations
//

#endif