C++ circular include(C++循环包含)
问题描述
我无法解决这个循环依赖问题;总是收到这个错误:不完整类型结构 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
...以及 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++循环包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++循环包含
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01