【发布时间】:2011-12-01 18:33:19
【问题描述】:
在 C++ 中,我遇到了循环依赖/不完整类型的问题。情况如下:
Stuffcollection.h
#include "Spritesheet.h";
class Stuffcollection {
public:
void myfunc (Spritesheet *spritesheet);
void myfuncTwo ();
};
Stuffcollection.cpp
void Stuffcollection::myfunc(Spritesheet *spritesheet) {
unsigned int myvar = 5 * spritesheet->spritevar;
}
void myfunc2() {
//
}
Spritesheet.h
#include "Stuffcollection.h"
class Spritesheet {
public:
void init();
};
Spritesheet.cpp
void Spritesheet::init() {
Stuffcollection stuffme;
myvar = stuffme.myfuncTwo();
}
- 如果我保留如上所示的包含,我得到编译器错误
spritesheet has not been declared在 Stuffcollection.h(第 4 行 以上)。我理解这是由于循环依赖。 - 现在,如果我将
#include "Spritesheet.h"更改为 Forward 在 Stuffcollection.h 中声明class Spritesheet;,我得到了 编译器错误invalid use of incomplete type 'struct Spritesheet'在 Stuffcollection.cpp 中(上面的第 2 行)。 - 同样,如果我在 Spritesheet.h 中将
#include "Stuffcollection.h"更改为class Stuffcollection;,我会收到编译器错误aggregate 'Stuffcollection stuffme' has incomplete type and cannot be defined在 Spritesheet.cpp 中(上面的第 2 行)。
我能做些什么来解决这个问题?
【问题讨论】:
-
重复stackoverflow.com/questions/7665912/double-include-solution/…(这是同一作者不久前提出的!)
-
@EdHeal:我对那个 Q 有最高的投票答案,它不是重复的。有细微差别,仔细看就知道了。
-
这不是您程序中的实际代码。此代码无法生成您指示的错误消息。请将您的程序缩减为一个最小的、完整的示例程序,并在此处复制粘贴(不重新键入)该代码。见sscce.org。
-
@Als - 我认为上一个问题对 .cpp 文件中的
#include来说是显而易见的。 -
@EdHeal:是的,但是 OP 不理解它,如果我们关闭这个重复的说法,他/她不会。
标签: c++ circular-dependency incomplete-type