[英]Purpose of Using namespace in C++
什么using namespace std;
包含?
由于IOstream头文件中存在所有与IO相关的函数,为什么我们应该同时使用IOStream和Std命名空间?
命名空间允许在名称下对类,对象和函数等实体进行分组。 这样,全局范围可以划分为“子范围”,每个范围都有自己的名称。
命名空间的格式是:
namespace identifier
{
entities
}
例如
// using
#include <iostream>
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main () {
using namespace first;
cout << x << endl;
cout << y << endl;
cout << second::x << endl;
cout << second::y << endl;
return 0;
}
您可以在http://www.cplusplus.com/doc/tutorial/namespaces/中阅读更多相关信息。
除了这里的其他答案之外,重要的是要注意using声明和using指令之间的区别。
using namespace std;
是using指令 ,允许在没有限定条件的情况下使用该命名空间中的所有名称。 例如:
using namespace std;
string myStdString;
cout << myStdString << endl;
这与以下形成对比:
using std::string;
是一个using声明 ,允许使用指定命名空间中的特定名称而无需限定。 以下内容无法编译:
using std::string;
string myStdString; // Fine.
cout << myStdString << endl; // cout and endl need qualification - std::
using
关键字受范围约束:
void Foo()
{
{
using namespace std;
string myStdString; // Fine.
}
string outOfScope; // Using directive out of scope.
std::string qualified; // OK
}
将一个using指令放在头文件的全局范围内通常是个坏主意 - 除非你非常确定任何包含该文件的内容都不会包含冲突的类名,并产生令人讨厌的副作用。
命名空间允许我们在名称下对一组全局类,对象和/或函数进行分组。 如果using namespace std
指定,则不必在整个代码中放置std::
。 程序将知道在std库中查找对象。 命名空间std包含标准C ++库的所有类,对象和函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.