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

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

using namespace std;

这条语句的作用是什么?

这个功能和"include "一样吗?

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命名空间四。所以你可以使用 cout 而不使用 std::。这可能会被误认为是更高效的编码。但是你会 运行 在某一时刻遇到问题。

在命名空间std中定义了成百上千的函数或常量等。大多数时候你不会为此烦恼。但是如果你一次性定义一个同名同参数的函数,你就很难发现错误。例如有std::find。您可能有机会定义相同的功能。这种情况下的编译器错误很痛苦。所以我强烈反对你使用 using namespace std;.

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

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

没有"using namespace std;"

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

和"using namespace std;"

#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 中(作为模板 class)。在 main() 中,当它看到名称 vector 的用法时,先前的 using namespace std 会导致编译器在 std 中查找与 vector 匹配的名称。它找到 std::vector,因此使用它 - 并且 v 然后具有实际类型 std::vector<int>

using 指令与预处理器的功能不同#include。在上面,#include <vector> 被预处理器替换为标准 header 的内容,名为 <vector>。 header 的内容声明了模板化的 std::vector class 和与之相关的东西。

如果从上面的示例中删除 #include <vector>,并保留 using namespace std,代码将无法编译,因为编译器无法看到 [=26] 的内容=].

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

当然可以把上面的代码改成

#include <vector>

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

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

在某些情况下不建议使用 using namespace std,但我会把它作为练习留给大家。