包括头文件与实现文件(C++)中的文件

Cod*_*asy 6 c++ implementation header

在头文件中包含头文件与在实现文件中包含头文件有什么区别?

这个

例如:

// test.h
#include"globals.h"

class Test
{
    Test();
};
Run Code Online (Sandbox Code Playgroud)

VS

//test.cpp
#include"globals.h"

Test::Test()
{
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 7

一般原则是您希望尽可能减少依赖关系,因此:

  • 如果您的接口(.h) 引用给定标头中的任何内容,则该标头需要 #included 在接口 (.h) 中

  • 如果你只在你的实现(.cpp)(而不是你的界面)中引用一个给定的头文件,那么你应该只在实现中#include那个头文件

  • 您还应该尝试只包含实际需要的 #include 标头,尽管在大型项目的生命周期中这可能难以维护

因此,对于上面的示例,如果您没有在 test.h 中从 globals.h 中引用任何内容,但是在 test.cpp 中确实引用了它,那么 #include 应该在 test.cpp 中。如果你在 test.h 中引用了 globals.h 中的任何内容,那么你需要在 test.h 中使用 #include。