"using namespace std;"在C++的作用是什么?
What is the function of "using namespace std;" in C++?
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
,但我会留下发现这一点作为一种练习。
- "using namespace std;"在C++的作用是什么?
- 此代码中的" "是什么,它的基本作用是什么?
- 在模板参数中使用 {} 在 type_trait{} 中时,其作用是什么<T>?
- <<、>>算子在循环中的作用是什么
- 在c++中,减号和加号对字符串的作用是什么
- 窄集(_cast)的作用是什么
- 在这种情况下,#define 的作用是什么?
- 遍历模板参数包,没有争论的专业化的作用是什么?
- 在 c++ 中,没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?
- 访问多个阵列时 CPU 缓存的作用是什么?
- 以下表达式的作用是什么:x = (a1,a2,..,n);
- 私人成员的作用是什么?
- 这段代码的作用是什么?
- *.exp文件的作用是什么
- ifstream::open()真正的作用是什么
- 如何在矩阵中使用指针.这行代码的作用是什么:int r=**(++b);
- 这个函数的作用是什么?与夹紧值有关
- 这个运算符()语法的作用是什么
- std::函数的模板参数中“const”修饰符和引用的作用是什么
- 字符串流在C++编程中的作用是什么