C/C++ 中的冗余#include?

发布于 2024-12-11 07:49:44 字数 336 浏览 0 评论 0原文

假设现在我有三个源文件:ClassA.hpp、ClassB.hpp 和 ClassC.hpp。

ClassB继承自ClassA,ClassC继承自ClassB。

因此,在 ClassB.hpp 中,我编写了 #include "ClassA.hpp"。 那么ClassC.hpp中除了包含ClassB.hpp之外,是不是还包含ClassA.hpp呢?

编写 Makefile 时,是否应该创建 ClassC.o 的 ClassA.oa 依赖项? 在cmake中——如果我不在ClassC.hpp中编写#include“ClassA.hpp”,ClassA.o将不会成为ClassC.o的依赖项,对吧?可以吗?

Suppose now I have three source files: ClassA.hpp, ClassB.hpp, and ClassC.hpp.

ClassB inherits from ClassA, and ClassC inherits from ClassB.

So, in ClassB.hpp, I wrote #include "ClassA.hpp".
Then, in ClassC.hpp, besides including ClassB.hpp, shall I also include ClassA.hpp?

When writing Makefiles, should I make a ClassA.o a dependency of ClassC.o?
And in cmake -- if I don't write #include "ClassA.hpp" in ClassC.hpp, ClassA.o will not be a dependency of ClassC.o, right? Is that ok?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

忘年祭陌 2024-12-18 07:49:44

ClassC.hpp是否需要ClassA.hpp的内容,暂时忽略ClassB.hpp?

如果是这样,那么是的,您应该包含它,而不是依赖于可能会改变的迂回意外包含。检查并设置正确的包含应该相对简单。依赖稍后可能会更改的另一个文件或行为是不好的做法,不应使用。

编辑:就问题所适用的继承而言,情况有些不同。在这种情况下,您可以依赖需要A的B,并且可以说您不直接依赖A(如果B更改为从Q继承,则C可能不再需要A)。您想要查看标头或类所依赖的内容,并包含提供该标头或类的文件。如果它直接依赖于某些东西,请直接包含它。

使用标头保护可以使多次包含标头变得无害,并且在较大的代码库中很常见。

Does ClassC.hpp require the contents of ClassA.hpp, disregarding ClassB.hpp for the time being?

If so, then yes, you should include it and not rely on a round-about accidental include that could change. Checking that and setting up the proper includes should be relatively simple. Relying on another file or behavior that may change later is poor practice, and should not be used.

Edit: In the case of inheritance, which the question applies to, things are a bit different. This is a case where you can rely on B requiring A, and it could be said you don't directly rely on A (if B changed to inherit from Q, C could no longer need A). You want to look at what a header, or class, depends on and include the file providing that. If it relies on something directly, include it directly.

Including a header multiple times can be made harmless with the use of header guards and is very common in larger code bases.

悍妇囚夫 2024-12-18 07:49:44

关于品牌,ClassC.o 不应依赖于 ClassA.o。它应该依赖于 ClassA.hpp,即使它是通过 ClassB.hpp 间接包含的,通常也会生成 ClassA.hpp。

如果 ClassB.hpp 依赖于 ClassA.hpp 中定义的内容,我喜欢让 ClassB.hpp 显式包含 ClassA.hpp。我认为这样更干净。

Regarding the make, ClassC.o should not depend on ClassA.o. It should have a dependency on ClassA.hpp, which will normally be generated even though it is included indirectly through ClassB.hpp.

I like to have ClassB.hpp include ClassA.hpp explicitly if it relies on stuff defined in ClassA.hpp. I think it is cleaner that way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文