gpt4 book ai didi

c++ - 循环依赖/不完整类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:20:34 25 4
gpt4 key购买 nike

在 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 尚未在 Stuffcollection.h 中声明(第 4 行以上)。我理解这是由于循环依赖。
  • 现在,如果我将 #include "Spritesheet.h" 更改为 Forward在 Stuffcollection.h 中声明 class Spritesheet;,我得到编译器错误 不完整类型“struct Spritesheet”的无效使用在 Stuffcollection.cpp 中(上面的第 2 行)。
  • 同样,如果我将 #include "Stuffcollection.h" 更改为 class
    Stuffcollection;
    在 Spritesheet.h 中,我得到编译器错误 aggregate
    'Stuffcollection stuffme' 的类型不完整,无法定义
    在 Spritesheet.cpp 中(上面的第 2 行)。

我该怎么做才能解决这个问题?

最佳答案

您应该在 Stuffcollection.cpp
中包含 Spritesheet.h只需在头文件而不是cpp文件中使用前向声明,即可解决头文件的循环依赖。源文件实际上没有循环依赖。

Stuffcollection.cpp 需要知道类 Spritesheet 的完整布局(因为您取消引用它),因此您需要包含定义类 的 header 该文件中的 Spritesheet

来自你之前的Q here ,我相信 Stuffcollection 类在 Spritesheet 头文件的类声明中使用,因此是上述建议的解决方案。

关于c++ - 循环依赖/不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7666665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com