我对此主题有一些疑问,但首先让我给您一些代码:

example.hpp

#ifndef EXAMPLE_H_
#define EXAMPLE_H_

using namespace std;

void say_something(string something);

#endif

example.cpp
#include <string>
#include <iostream>
#include "example.hpp"

void say_something(string something)
{
    cout << something << '\n';
}

main.cpp
#include <iostream>
#include <string>
#include "example.hpp"

using namespace std;

int main()
{
    string hello = "Hello world!";
    say_something(hello);

    return 0;
}

现在,我的问题是:
  • 我应该将 example.cpp 需要的所有头文件放在头 example.hpp 头中还是应该像上面的示例一样将它们保留在 example.cpp 中?
  • 在这种情况下C++的工作方式:在 main.cpp example.cpp 中都包含了'string'和'iostream'... C++编译器是否会链接(或您将使用的任何术语找到更合格的)程序两次与字符串和iostream header ?我应该只将字符串和iostream header 放在示例中。cpp
  • 最后,我应该将要用于示例 header 的 namespace 放在 header 本身( example.hpp )还是实现中( example.cpp )?
  • 最佳答案



    保持头文件最少。

    头文件提供函数声明。函数声明取决于<string>中的内容,而不取决于<iostream>中的内容。因此,头文件应包括<string>而不是<iostream>

    如果头文件包含不必要的内容,则头文件的用户也将包含那些不必要的内容。



    C++源不与标题链接。每当您编写#include <string>时,预处理器(概念上)都会复制整个名为“string”的头文件,并粘贴在#include <string>行中。预处理发生在编译和链接之前。



    切勿在头文件的全局范围内写入using namespace std;。由于#include的复制和粘贴性质,using指令将感染其他包含 header 的文件。如果有一个文件想要使用say_something但不想使用using namespace std怎么办?

    关于c++ - 在C++中使用头文件的正确方法是哪种?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35762699/

    10-11 22:35
    查看更多