"using namespace std;"在C++的作用是什么?

What is the function of "using namespace std;" in C++?

本文关键字:作用 是什么 C++ using namespace std      更新时间:2023-10-16
using namespace std;

这句话的作用是什么?

这是否具有与"包含"相同的功能?

c++中的一个概念是命名空间。这会以某种方式组织您的代码。

using namespace std;现在在做什么?让我们通过示例来探讨这一点。

#include <iostream>
int main() {
std::cout << "Hello World" << std::endl; // important line
return 0;
}

您会在带有注释的行中看到std关键字。这称为命名空间。所以你告诉编译器,你想使用命名空间std中的cout

using namespace std;

#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl; // important line
return 0;
}

在那里,您告诉编译器,在此范围内打开std命名空间四个u。因此,您可以在没有std::的情况下使用cout。这可能会被误认为对代码更有效。但是你会在某一时刻遇到问题。

在命名空间中std定义了函数或常量等。大多数时候你不会为此烦恼。但是,如果您在某一点上定义具有相同名称和参数的函数,则几乎无法找到错误。例如,有std::find.您可能有可能定义相同的函数。在这种情况下,编译器错误是一种痛苦。所以我强烈反对你使用using namespace std;.

它与"include"的功能不同。此语句允许您访问 std 命名空间中定义的任何类、函数或类型,而无需在类或函数名称前键入"std::"。

示例:如果要在 std 命名空间中声明字符串类型的变量

没有"使用命名空间标准;">

#include <string>
...
std::string str1;
std::string str2;

使用"使用命名空间标准;">

#include <string>
using namespace std;
...
string str1;
string str2

using 指令using namespace std使命名空间内的名称std当前作用域中使用的匹配名称的候选名称。

例如,在

#include <vector>
using namespace std;
int main()
{
vector<int> v;
}

名称vector存在于命名空间std中(作为模板化类)。main()当它看到名称的用法时vector,前面的using namespace std会导致编译器在std中查找与vector匹配的名称。 它找到std::vector,所以使用它 - 然后v有实际的类型std::vector<int>

using 指令与预处理器#include的功能不同。 在上面,#include <vector>被预处理器替换为名为<vector>的标准标头的内容。 该标头的内容声明模板化std::vector类以及与之关联的内容。

如果从上面的示例中删除#include <vector>,并将using namespace std保留在原位,则代码将无法编译,因为编译器看不到<vector>的内容。

相反,如果删除using namespace std但保留#include <vector>,则代码将无法编译,因为名称vector位于命名空间std中,并且不会在该命名空间中搜索与vector匹配的名称。

当然,您可以将上面的代码更改为

#include <vector>
int main()
{
std::vector<int> v;
}

在这种情况下,std::vector的用法显式告诉编译器在命名空间std中查找名称vector

在某些情况下,不建议使用using namespace std,但我会留下发现这一点作为一种练习。