[英]Should a header file include other header files, or leave it to the implementation?
So I can get everything to compile, and I understand (I think) how include guards prevent the same definitions from being pulled twice, but what I don't know is if my header file should also include the header file for the class it uses, if my class file already includes it.所以我可以编译所有内容,并且我理解(我认为)包含守卫如何防止相同的定义被拉两次,但我不知道我的头文件是否还应该包含它使用的类的头文件,如果我的类文件已经包含它。
Child.hpp子.hpp
// Child.hpp
#ifndef CHILD_H
#define CHILD_H
class Child {
public:
Child();
};
#endif
Child.cpp子文件
// Child.cpp
#include "Child.hpp"
Child::Child() {
// example
}
Parent.hpp父.hpp
Should I also include Child.hpp here even though it's already included in Parent.cpp?即使 Child.hpp 已经包含在 Parent.cpp 中,我也应该在这里包含它吗? I understand the header guard would prevent Child being defined twice, but is it considered best practice?
我知道标题守卫会阻止 Child 被定义两次,但它被认为是最佳实践吗? Or should I exclusively include Child.hpp here?
或者我应该在这里只包含 Child.hpp 吗?
// Parent.hpp
#ifndef PARENT_H
#define PARENT_H
class Parent {
public:
Parent();
Parent(Child child);
};
#endif
Parent.cpp父.cpp
// Parent.cpp
#include "Child.hpp"
#include "Parent.hpp"
int main() {
Parent parent;
return 0;
}
Parent::Parent() {
// example
}
Parent::Parent(Child child) {
// example
}
We were just given one example in class, and it essentially said that in Parent.cpp
it should include Parent.hpp
(makes sense) and Child.hpp
.我们在课堂上只举了一个例子,它本质上是说在
Parent.cpp
它应该包括Parent.hpp
(有意义)和Child.hpp
。
It would seem I would want to include Child.hpp
in Parent.hpp
as the Parent
class relies on the Child
class, but either way Child.hpp
gets included.这似乎我想包括
Child.hpp
在Parent.hpp
作为Parent
类依赖于Child
类,但无论哪种方式Child.hpp
被包括在内。
If Parent
has any instances of Child
, yes you must include the header to Child.hpp
.如果
Parent
有任何Child
实例,是的,您必须将标题包含到Child.hpp
。
class Parent {
public:
Parent();
Parent(Child child); // Need full include, complete type used
Child c; // Need full include, complete type used
};
If Parent
only had pointers or references to Child
you could get away with simply forward-declaring Child
, then doing the include in Parent.cpp
.如果
Parent
只有对Child
指针或引用,您可以简单地向前声明Child
,然后在Parent.cpp
进行包含。
class Child; // Forward declaration
class Parent {
public:
Parent();
Parent(Child* child);
Child* pc; // Incomplete type ok if pointer or reference
};
In general, you should avoid including headers inside other headers unless absolutely necessary.通常,除非绝对必要,否则您应该避免在其他标头中包含标头。 At best, it increases build times unnecessarily.
充其量,它会不必要地增加构建时间。 At worst, it can lead to circular dependencies.
在最坏的情况下,它会导致循环依赖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.