我对此主题有一些疑问,但首先让我给您一些代码:
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;
}
现在,我的问题是:
最佳答案
保持头文件最少。
头文件提供函数声明。函数声明取决于<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/