【问题标题】:Do you need to explicitly include headers that other headers already include themselves?您是否需要明确包含其他标头已经包含自己的标头?
【发布时间】:2016-09-05 00:37:25
【问题描述】:

给定一个头文件foo.h:

#include <bar>

// ...

还有一个文件baz.cpp:

#include "foo.h"

// ...

您是否需要将bar 标头显式包含到baz.cpp 中才能使用它?或者你可以开始使用它,因为它包含在foo.h 中?

【问题讨论】:

  • 如果你直接在main.cpp中使用来自algorithm的东西,那么是的;否则不会。

标签: c++ header include


【解决方案1】:

如果main.cpp 使用任何函数或类,或者&lt;algorithm&gt; 中定义的任何其他内容,则需要将#include &lt;algorithm&gt; 添加到main.cpp。

其他翻译单元使用什么无关紧要。

【讨论】:

    【解决方案2】:

    不,你不需要。将“#include”视为在该行复制和粘贴包含文件的全部内容的方向。

    其他.h:

    #include <string>
    #include <vector>
    
    std::string getString()
    {
        return "A String";
    }
    

    main.cpp:

    #include <iostream>
    #include "other.h"
    
    
    int main()
    {
        std::vector<std::string> vec{getString(), getString()};
    
        for (auto &it : vec) {
            std::cout << it << std::endl;
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2021-01-25
      相关资源
      最近更新 更多