头文件应该包括其他头文件,还是由实现来决定
Should a header file include other header files, or leave it to the implementation?
因此,我可以编译所有内容,并且我理解(我认为)include保护程序如何防止相同的定义被拉两次,但我不知道的是,如果我的类文件已经包括了它,我的头文件是否也应该包括它所使用的类的头文件。
Child.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
我是否也应该在这里包括Child.hpp,尽管它已经包含在Parent.cpp中了?我知道头部保护可以防止Child被定义两次,但这被认为是最佳实践吗?还是我应该在这里只包含Child.hpp?
// Parent.hpp
#ifndef PARENT_H
#define PARENT_H
class Parent {
public:
Parent();
Parent(Child child);
};
#endif
Parent.cpp
// Parent.cpp
#include "Child.hpp"
#include "Parent.hpp"
int main() {
Parent parent;
return 0;
}
Parent::Parent() {
// example
}
Parent::Parent(Child child) {
// example
}
我们在课堂上只举了一个例子,它本质上说在Parent.cpp
中应该包括Parent.hpp
(有意义)和Child.hpp
。
我似乎想在Parent.hpp
中包含Child.hpp
,因为Parent
类依赖于Child
类,但无论哪种方式,都会包含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
};
如果Parent
只有指向Child
的指针或引用,那么只需向前声明Child
,然后在Parent.cpp
中执行include就可以了。
class Child; // Forward declaration
class Parent {
public:
Parent();
Parent(Child* child);
Child* pc; // Incomplete type ok if pointer or reference
};
通常,除非绝对必要,否则应避免在其他标头中包含标头。充其量,它会不必要地增加构建时间。最坏的情况是,它可能导致循环依赖。
相关文章:
- 在实现文件中使用头文件的通用 lambda
- 在文件上实现迭代器
- C++头文件和类实现出现问题
- 在文件夹迭代上实现 RAII
- 如何使用命令提示符、记事本和 MinGW 使用主文件、头文件和实现文件编译C++程序?
- 用于 Windows 写入临时文件的 mkstemp() 实现
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- Linux 源代码中普通磁盘文件的"轮询"功能在哪里实现?
- 在 *.cpp 文件中实现的 c++ 函数/方法永远不会内联扩展吗?
- 在实现文件中使用模板参数声明方法
- 在头文件中使用opencv类型来实现未定义的标识符
- 模板实现文件中的匿名命名空间
- 创建单独的实现文件和头文件
- 多文件类实现Cpp
- Reader类实现中的文件读取错误
- MEX文件实现特征库伪内函数崩溃
- openssl rc4 命令行加密和 cpp 文件实现 rc4 之间的区别
- 从其他头文件实现结构
- c++头文件-实现-头文件-实现依赖链
- 内存映射文件实现