循环依赖项/不完整类型
Circular Dependencies / Incomplete Types
在C++中,我遇到了循环依赖项/不完整类型的问题。情况如下:
物料收集.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();
}
- 如果我保留如上所示的includes,我会得到编译器错误Stuffcollection.h中的
spritesheet has not been declared
(中的第4行以上(。我理解这是由于循环依赖 - 现在,如果我将
#include "Spritesheet.h"
更改为前进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行(
我能做些什么来解决这个问题?
您应该在Stuffcollection.cpp
中包含Spritesheet.h
只需在头文件中使用正向声明,而不是在cpp文件中使用,即可解决头文件的循环依赖关系。源文件实际上没有循环依赖关系。
Stuffcollection.cpp
需要知道类Spritesheet
的完整布局(因为你取消了对它的引用(,所以你需要在该文件中包括定义类Spritesheet
的头。
根据您之前的Q此处,我认为Stuffcollection
类用于Spritesheet
头文件的类声明,因此使用了上述提出的解决方案。
将此表单用于嵌套包含:
物料收集.h
#ifndef STUFFCOLLECTION_H_GUARD
#define STUFFCOLLECTION_H_GUARD
class Spritesheet;
class Stuffcollection {
public:
void myfunc (Spritesheet *spritesheet);
void myfuncTwo ();
};
#endif
Stuffcollection.cpp
#include "Stuffcollection.h"
#include "Spritesheet.h"
void Stuffcollection::myfunc(Spritesheet *spritesheet) {
unsigned int myvar = 5 * spritesheet->spritevar;
}
void Stuffcollection::myfuncTwo() {
//
}
精灵表.h
#ifndef SPRITESHEET_H_GUARD
#define SPRITESHEET_H_GUARD
class Spritesheet {
public:
void init();
};
#endif
精灵表.cpp
#include "Stuffcollection.h"
#include "Spritesheet.h"
void Spritesheet::init() {
Stuffcollection stuffme;
myvar = stuffme.myfuncTwo();
}
我遵循的一般规则:
- 不要包含包含中的包含,伙计。如果可能的话,更喜欢远期申报。
- 例外:将系统包含在您想要的任何位置
- 让CPP包含它所需要的一切,而不是依赖于H递归地包含它的文件
- 始终使用防护罩
- 切勿使用
pragma
Spritesheet.h
不需要包括Stuffcollection.h
,因为在Spritesheet
的类声明中没有使用Stuffcollection
。将包含行移到Spritesheet.cpp
,您应该会没事的。
相关文章:
- 如何从C++中的依赖类型中获得它所依赖的类型
- 将依赖名称显式标记为类型名和模板的奇怪之处
- 当基类是依赖类型时,这是一个缺陷吗
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 使用 'typename' 关键字将非类型视为依赖上下文中的类型
- 为什么依赖模板类型在部分专用化中不可推导?
- 为什么即使直到最后才定义实际类型,也可以将依赖名称视为完整
- 为什么不需要在 C++20 中的依赖类型之前指定"typename"?
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- 类型依赖于可变参数模板的类
- 类型依赖模板名称
- 模板类型依赖和继承
- C++中的循环类型依赖项死锁
- c++ 中带有容器迭代器的循环类型依赖关系(GCC 失败,而 MSVC 正常)
- C++使变量类型依赖于用户输入
- 使返回类型依赖于调用源
- 如何专用化基于类型依赖类型的C++模板化类函数
- 将 POD 联合双关到基本类型:依赖于实现或符合标准
- 使用类型依赖模板名的声明
- 非类型模板参数,其类型依赖于另一个参数