如何定义名称空间以及编译器如何处理名称空间

how do define namespace and how does the compiler deal with namespace?

本文关键字:空间 何处理 处理 编译器 何定义 定义      更新时间:2023-10-16

今天我看到C++命名空间,遇到了一个问题。编译器对命名空间做什么?例如:我们写

#include<iostream>
using namespace std;

那么问题来了,iostream文件和namespace std之间的关系是什么?std在哪里定义,在什么文件中?当我使用#include <iostream.h>时,我知道编译器会将iostream.h中的声明(如"cout"、"cin"等)带到我的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
}

这种情况就像在库中搜索一样。iostream是书,std是页,cout是行或段落。

注意:同一页面可以存在于多本书中

请在此处阅读有关命名空间的信息。