gpt4 book ai didi

c++ - Main.cpp中包含头文件有限制吗?

转载 作者:行者123 更新时间:2023-11-30 05:37:14 25 4
gpt4 key购买 nike

我刚刚设法解决了我自己的问题,解释了 here .我不明白的是它背后的原因。基本上在将一个工作程序拆分成一个 makefile 之后,所有包含都在正确的位置,一个特定的对象构造调用停止工作。

解决方案最终是将 #include "filename.h"在 main.cpp 文件中的 10 个左右 #includes 列表中向上移动。

这是否意味着存在某种约束?我不知道其中一个,并且自从进行此更改后,现在位于底部的另一个 header 仍然可以正常工作。

Pastebin

编辑:应某些用户的要求,我添加了为我产生错误的最少代码。虽然它仍然只有 300 多行......代码顶部的注释解释了如何使错误发生,但需要将代码拆分为单独的文件并使用 makefile。

最佳答案

确实存在限制:一个包含文件可能需要在另一个包含文件中定义的类。因此,您必须确保文件以正确的顺序包含在内。

示例:

//======== File A.h ==========
class A {
...
};

//======== File B.h ==========
class B : public A { // class B needs A to be defined first !!
...
};

//======== File main.cpp that works ========
#include "A.h"
#include "B.h" // ok: relies on A and A is already defined
...

//======== File ouch.cpp that fails ========
#include "B.h" // not ok: relies on A but A is not yet defined !!
#include "A.h"
...

但幸运的是,有一些好的做法可以避免此类陷阱:在您的 header 中使用 include guards,并且在任何 header 中,预防性地包含由于依赖关系而需要的其他 header 。这里是nice article解释这个。

关于c++ - Main.cpp中包含头文件有限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33318969/

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