是否需要显式地包含其他标头已经包含它们自己的标头?

Do you need to explicitly include headers that other headers already include themselves?

本文关键字:自己的 包含它 其他 包含 是否      更新时间:2023-10-16

给定头文件foo.h:

#include <bar>
// ...

和文件baz.cpp:

#include "foo.h"
// ...

你需要明确地包括bar头到baz.cpp为了使用它?或者你可以开始使用它,因为它包含在foo.h中?

如果main.cpp使用了<algorithm>中定义的任何函数或类,则需要将#include <algorithm>添加到main.cpp中。

其他翻译单元使用什么是不相关的

不,你不需要。可以把"#include"看作是复制和粘贴所包含文件的全部内容的指示。

other.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;
}
相关文章: