由于命名空间std已经有包含函数定义的c库(如果我是对的),那么为什么我们在它上面包含头文件?由于命名空间std包含c标准库,因此我没有理由单独包含它的声明.
解决方法
当你做#include< iostream>它会导致一组类和其他内容包含在源文件中.对于iostream和大多数标准库头文件,他们将这些内容放在名为std的命名空间中.
所以#include< iostream>的代码看起来像这样:
namespace std {
class cin { ... };
class cout { ... };
class cerr { ... };
class clog { ... };
...
}
所以在这一点上,你可以写一个看起来像这样的程序:
#include <iostream>
int main() {
std::cout << "hello\n";
return 0;
}
现在,有些人觉得std :: cout太冗长了.所以他们这样做:
#include <iostream>
using namespace std;
int main() {
cout << "hello\n";
return 0;
}
就个人而言,我建议不要这样做,如果你真的觉得std :: cout太冗长了,那么我建议你使用较小的using语句.
#include <iostream>
using std::cout;
int main() {
cout << "hello\n";
return 0;
}
如果你想知道为什么我会建议不要使用命名空间std,那么我会转发你在stackoverflow上的以下两个帖子:
> C++ Distance Function Keeps Returning -1
> Why is “using namespace std” considered bad practice?