C ++循环包括

时间:2013-07-25 17:52:04

标签: c++ header compiler-errors circular-dependency

我无法解决这个循环依赖问题;总是得到这个错误: “无效使用不完整类型的结构GemsGame” 我不知道为什么编译器不知道GemsGame的声明,即使我包含了gemsgame.h 两个类都相互依赖(GemsGame存储GemElements的向量,GemElements需要访问这个相同的向量)

以下是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:

#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

4 个答案:

答案 0 :(得分:2)

删除#include指令,已经声明了前向类。

如果您的A级在其定义中需要了解B类的详细信息,那么您需要包含B类的标题。如果类A只需要知道类B存在,例如当类A只保存指向类B实例的指针时,那么它就足以进行前向声明,在这种情况下,不需要#include

答案 1 :(得分:1)

如果您使用指针并且函数是内联的,则需要完整类型。如果为实现创建cpp文件,则可以避免循环依赖(因为类中的任何一个都不需要在其标题中包含彼此.h)

这样的事情:

你的标题:

#ifndef GEMELEMENT_H_INCLUDED
#define GEMELEMENT_H_INCLUDED

class GemsGame;

class GemElement {
    private:
        GemsGame* _gemsGame;

    public:
        GemElement();
};


#endif // GEMELEMENT_H_INCLUDED

你的cpp:

#include "GenGame.h"
GenElement::GenElement()
{
   _gemsGame = application.getCurrentGame();
   _gemsGame->getGemsVector();
}

答案 2 :(得分:1)

两种出路:

  1. 将相关类保留在同一个H文件中
  2. 将依赖转换为抽象接口:GemElement实现IGemElement并期待IGemsGame,GemsGame实现IGemsGame并包含IGemElement指针的向量。

答案 3 :(得分:1)

请看这个主题的最佳答案:When can I use a forward declaration?

他真的解释了你需要知道的有关前向声明的所有内容,以及你能够和不能用前面声明的类所做的事情。

看起来您正在使用类的前向声明,然后尝试将其声明为其他类的成员。这会失败,因为使用前向声明会使其成为不完整的类型。