C++ circular include(C++ 循环包含)
问题描述
我无法解决这个循环依赖问题;总是得到这个错误:不完整类型结构 GemsGame 的无效使用"我不知道为什么编译器不知道 GemsGame 的声明,即使我包含 gemsgame.h两个类相互依赖(GemsGame存储了一个GemElements的vector,GemElements需要访问这个vector)
I can't solve this circular dependency problem; always getting this error: "invalid use of incomplete type struct GemsGame" I don't know why the compiler doesn't know the declaration of GemsGame even if I included gemsgame.h Both classes depend on each other (GemsGame store a vector of GemElements, and GemElements need to access this same vector)
这是GEMELEMENT.H的部分代码:
Here is partial code of GEMELEMENT.H:
#ifndef GEMELEMENT_H_INCLUDED
#define GEMELEMENT_H_INCLUDED
#include "GemsGame.h"
class GemsGame;
class GemElement {
private:
GemsGame* _gemsGame;
public:
GemElement{
_gemsGame = application.getCurrentGame();
_gemsGame->getGemsVector();
}
};
#endif // GEMELEMENT_H_INCLUDED
...GEMSGAME.H:
...and of GEMSGAME.H:
#ifndef GEMSGAME_H_INCLUDED
#define GEMSGAME_H_INCLUDED
#include "GemElement.h"
class GemsGame {
private:
vector< vector<GemElement*> > _gemsVector;
public:
GemsGame() {
...
}
vector< vector<GemElement*> > getGemsVector() {
return _gemsVector;
}
}
#endif // GEMSGAME_H_INCLUDED
推荐答案
去掉 #include
指令,你已经声明了类.
Remove the #include
directives, you already have the classes forward declared.
如果您的 A 类需要在其定义中了解 B 类的详细信息,那么您需要包含 B 类的标题.如果 A 类只需要知道 B 类的存在,比如 A 类只持有一个指向 B 类实例的指针,那么前向声明就足够了,在这种情况下 #include
不是需要.
If your class A needs, in its definition, to know something about the particulars of class B, then you need to include class B's header. If class A only needs to know that class B exists, such as when class A only holds a pointer to class B instances, then it's enough to forward-declare, and in that case an #include
is not needed.
这篇关于C++ 循环包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 循环包含
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01