>placeable.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,其中再次包含 placeable.h。
我能想到的唯一解决方案是将可放置*放在新标题中,使其成为静态/全局,然后将这个新标题包含在 game.h 和 selectable.h 中。
很抱歉,我不喜欢在上面的代码中包含标题保护。我认为这是显而易见的。由于继承,标头保护在这种情况下无济于事,前向声明也是如此。
必须时才包含标头
优先使用前向声明,而不是包括:
您只需要包含类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;
...
};
添加标题保护。
这意味着您没有正确封装设计的功能。 它应该是更高层次包括较低层次,而不是同级包括同级。 如果游戏是更高级别,则可选不应包括 game.h。
已解决的问题。它被称为标题护罩。在所有头文件中尝试此操作:
#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;
};
有两个问题:
- 循环标头依赖项。解决方案 - #ifndef ...
- 为未知类型分配空间。解决方案 - 类可放置;
在此处查看更多内容
在每个头文件中使用标头保护以避免此问题。通常,您的头文件应如下所示:
#ifndef PLACEABLE_H
#define PLACEABLE_H
//
// Class definitions and function declarations
//
#endif