问题描述
我无法解决这个循环依赖问题;总是收到这个错误:不完整类型结构 GemsGame 的无效使用"我不知道为什么编译器不知道 GemsGame 的声明,即使我包含了 gemsgame.h两个类相互依赖(GemsGame 存储了一个 GemElements 的向量,而 GemElements 需要访问同一个向量)
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.hBoth 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++循环包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!