循环依赖/不完整类型

Ben*_*Ben 6 c++ circular-dependency incomplete-type

在 C++ 中,我遇到了循环依赖/不完整类型的问题。情况如下:

Stuffcollection.h

#include "Spritesheet.h";
class Stuffcollection {
    public:
    void myfunc (Spritesheet *spritesheet);
    void myfuncTwo ();
};
Run Code Online (Sandbox Code Playgroud)

东西集合.cpp

void Stuffcollection::myfunc(Spritesheet *spritesheet) {
    unsigned int myvar = 5 * spritesheet->spritevar;
}
void myfunc2() {
    //
}
Run Code Online (Sandbox Code Playgroud)

精灵表.h

#include "Stuffcollection.h"
class Spritesheet {
    public:
    void init();
};
Run Code Online (Sandbox Code Playgroud)

精灵表.cpp

void Spritesheet::init() {
    Stuffcollection stuffme;
    myvar = stuffme.myfuncTwo();
}
Run Code Online (Sandbox Code Playgroud)
  • 如果我保留如上所示的包含,我会spritesheet has not been declared在 Stuffcollection.h(上面的第 4 行)中收到编译器错误 。我理解这是由于循环依赖。
  • 现在,如果我更改#include "Spritesheet.h"class Spritesheet;Stuffcollection.h 中的前向声明,则会在 Stuffcollection.cpp 中收到编译器错误invalid use of incomplete type 'struct Spritesheet' (上面的第 2 行)。
  • 同样,如果我在 Spritesheet.h 中更改#include "Stuffcollection.h"class Stuffcollection;,则会在 Spritesheet.cpp 中收到编译器错误aggregate 'Stuffcollection stuffme' has incomplete type and cannot be defined (上面的第 2 行)。

我能做些什么来解决这个问题?

sth*_*sth 2

Spritesheet.h不需要包含Stuffcollection.h,因为Stuffcollection的类声明中使用了no Spritesheet。将包含行移至相反Spritesheet.cpp,应该没问题。