今天我看到了 C++ 命名空间,我遇到了一个问题。 编译器对命名空间做了什么? 例如: 我们写
#include<iostream>
using namespace std;
那么问题来了,
iostream
文件和namespace std
之间有什么关系呢? std
定义在哪里,在哪个文件中?当我使用 #include <iostream.h>
时,我知道编译器会将 iostream.h 中的声明(例如“cout”、“cin”.etc)带到我的 cpp 文件中。
你能给一些建议吗?
阅读本文,它解释了命名空间 http://www.cplusplus.com/doc/tutorial/namespaces/
<iostream>
包含来自 namespace
std
的项目。您可以将命名空间视为方法、类定义和变量的分组。使用命名空间可以更轻松地按功能进行分组。
using
指令只是导入全局命名空间中命名空间的所有内容。但你不必使用它:
您可以使用:
using namespace std;
cout << "whatever";
或
std::cout << "whatever";
这样做的原因是编译器不知道
cout
在命名空间之外。
将其视为声明如下:
//file <iostream>
namespace std
{
//declaration of cout
}
//file <vector>
namespace std
{
//declaration of vector
}