您是否需要明确包含其他头文件已经包含的头文件?

问题描述 投票:0回答:2

给定一个头文件 foo.h:

#include <bar>

// ...

还有一个文件 baz.cpp:

#include "foo.h"

// ...

你是否需要明确包括 bar 头部进入 baz.cpp 才能使用它?或者你可以直接开始使用它,因为它包含在 foo.h?

c++ header include
2个回答
2
投票

你需要添加 #include <algorithm>main.cpp 如果 main.cpp 使用任何函数或类,或其他任何定义在 <algorithm>.

其他翻译单位用什么是不相关的。


2
投票

不,你不需要。把 "#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.