本文介绍了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.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++ 循环包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 06:39