把包括在所有正确的地方

Putting includes in all the right places

因此,我们使用 #include 告诉 compiler/linker 在哪里可以找到 class 的所有相关代码。

看看这个:

ClassC.h:
    #include "ClassA.h";

ClassD.h:
    #include "ClassC.h"

假设我们在 ClassD 中使用了 ClassA,但与 ClassC 没有任何关联。我们通过包含 ClassC 隐含地包含了它,所以不会抛出任何错误。但是,如果代码更改并且不再需要 ClassC(因此我们删除了 #include "ClassC.h"),我们将得到未定义的引用错误,因为 ClassA 现在未被引用。

有没有办法让 compiler/linker 查看每个 *.cpp 并独立分配 *.h,而不查看包含的 .h 文件?

如果是这种情况,它不会查看 ClassC.h 并看到它包含 ClassA.h,而是抛出一个错误或至少一个警告告诉我我没有包含 ClassA.h。这更有意义,因为据 class ClassD 所知,ClassAClassC 彼此没有联系(在设定假设下我使用 ClassA 独立于 ClassC).

我认为以这种方式编写的代码会更稳定,更易于更改。不是吗?

此外,假设我们构建了一个项目,并且它有效。如果我们在代码中比之前引用的更早引用一些 class(X),如果它使用的是从其他来源包含的其他 class(Y),我们可能会收到错误在程序中的那个点和之前第一次出现的 class 之间。如果我们将 include 与显式使用它的每个头文件更紧密地联系在一起,这样的错误将永远不会出现。

我知道我自己可以跟踪所有这些,但在较大的项目中很容易错过一些或更多,即使是中型项目。此外,拥有 error/warning 将使它更易于管理。

我知道我让事情变得有点复杂,但这对我来说似乎是一个很好的做法。

这甚至是个好主意,能否以某种方式在 compiler/linker 选项中设置它(例如 CodeBlocks 中的 GNU gcc 编译器)?

Let's say we use ClassA in our ClassD, but in a way that is in no way connected to ClassC. We have implicitly included it by including ClassC, so no error is thrown. However, should the code change and ClassC is no longer needed (and we remove the #include "ClassC.h" because of that), we'd get undefined reference error since ClassA is now unreferenced.

如果您需要在 ClassD 中使用 ClassA,那么 明确地 #include "ClassA.h" 在您的 ClassD.h 中。 不要依赖隐式包含链。