C ++循环包括 [英] C++ circular include
问题描述
我不能解决这个循环依赖问题;总是得到这个错误:
无效使用不完全类型struct 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.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
... of 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 $不需要c $ c>。
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 ++循环包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!