本文介绍了C++ 循环头文件依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题:假设我有一个头文件/源文件集和一个头文件集如下

I had a question: Supposed I have a header/source file set and a header set as follows"

BaseCharacter.h 和 BaseCharacter.cpp 和 EventTypes.h

BaseCharacter.h and BaseCharacter.cpp and EventTypes.h

BaseCharacter.h 使用 EventTypes.h 中定义的结构和 typedef,但 EventTypes.h 必须了解 BaseCharacter.h 中定义的 BaseCharacter 类.这会产生循环依赖,我很确定这会阻止我的程序编译.如果我取出 EventTypes.h 和所有依赖 EventTypes.h 中的东西的方法,我的程序编译得很好.但是如果我添加了 EventTypes.h,它和每个引用 BaseCharacter.h 的文件都会抱怨它找不到 BaseCharacter 类.

BaseCharacter.h makes use of structs and typedefs defined in EventTypes.h, but EventTypes.h has to be aware of the BaseCharacter class defined in BaseCharacter.h. This creates a cyclical dependency and I'm pretty sure that's whats stopping my program from compiling. If I take out EventTypes.h and all the methods that rely on the stuff in EventTypes.h, my program compiles fine. But if I added EventTypes.h, it, and every file referencing BaseCharacter.h will complain that it can't find the BaseCharacter class.

有没有办法解决这种依赖关系,或者这不是导致我的问题的原因吗?

Is there a way around this dependency or would this not be what's causing my problem?

我使用 MSVC 2010 作为我的编译器

I'm using MSVC 2010 as my compiler

推荐答案

前向声明.

在 EventTypes.h 中,删除包含并添加:

In EventTypes.h, remove the include and add:

类 BaseCharacter;

请注意,您只能在 EventTypes.h 中使用对 BaseCharacter 的引用和指针,例如,您不能使用有一个带有 BaseCharacter myChar; 成员变量的结构.

Note that you can only use references and pointers to BaseCharacter within EventTypes.h, you cannot e.g. have a struct with a BaseCharacter myChar; member variable.

这篇关于C++ 循环头文件依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 20:14