【问题标题】:C++ circular includeC++ 循环包含
【发布时间】:2013-07-25 18:36:06
【问题描述】:

我无法解决这个循环依赖问题;总是得到这个错误: “不完整类型结构 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

【问题讨论】:

  • 如果你有一个前向声明,你不应该也包括它。从您所展示的内容来看,两者都只需要前向声明。

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


【解决方案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】:

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

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

    【讨论】:

      【解决方案3】:

      两条出路:

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

      【讨论】:

        【解决方案4】:

        看这个话题的置顶答案:When can I use a forward declaration?

        他真的解释了你需要知道的关于前向声明的一切,以及你可以和不能对你前向声明的类做什么。

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

        【讨论】:

          猜你喜欢
          • 2013-09-19
          • 1970-01-01
          • 2011-03-23
          • 2011-06-08
          • 1970-01-01
          • 1970-01-01
          • 2017-11-07
          • 2013-12-27
          • 2016-03-19
          相关资源
          最近更新 更多