交叉引用和循环依赖关系.标头间接包含自身
Cross reference and circular dependency. Header including itself indirectly
>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
相关文章:
- (Wix 安装程序)如何包含自定义操作依赖项
- 在包含窗口标头时难以解决循环依赖关系问题
- 为什么包含需要进一步的依赖关系?
- 派生自嵌套在类模板中的类模板,所有这些都包含在类模板中
- 在Visual Studio代码中包含自定义c++库的问题
- 替换包含已弃用的一元函数的自定义模板
- 如何在 RANSAC 平面估算器中包含自定义约束/排名?
- 如何破坏包含自指指针的对象
- 如何在包含自定义对象的容器中使用分区函数C++
- C 发布的矢量包含自定义类的内存
- 如何比较/排序包含自定义 typedef 的列表容器的元素
- 将包含自定义项的部分添加到类文档中
- C++ 不能在包含自定义结构的列表中使用push_back
- 如何包含自编译库中的标头
- 如何在 Linux 的C++文件中包含自定义头文件
- boost sharedmemory deque容器包含自定义类
- 如何在C++程序中包含自定义文件
- 在包含自定义类型的集合中查找
- 包含自定义头文件时出现编译器错误
- 循环访问包含自定义类C++的向量