简体   繁体   English

C++ 中的“使用命名空间::std”是什么

[英]What is "using namespace::std" in C++

I am reading some code snippets from others and I find a line:我正在阅读其他人的一些代码片段,我找到了一行:

using namespace::std;

I suspect its purpose is using namespace std;我怀疑它的目的是using namespace std; , with some typos. , 有一些错别字。 But to my surprise the compiler accepts this code without any complaint.但令我惊讶的是,编译器毫无怨言地接受了这段代码。 I build with:我用:

$ g++ --version
g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0

$ /usr/bin/g++ ${SRC} -std=c++11 -pthread -Wall -Wno-deprecated -o ${OUT}

I wonder why is this code valid, and what effects will it make?我想知道为什么这段代码有效,它会产生什么影响? I suspect it is a bad practice.我怀疑这是一种不好的做法。

It's just same as using namespace::std;这与using namespace::std;相同。 , then has the same effect with using namespace std; ,则与using namespace std; . .

As the syntax of using-directives :作为using-directives的语法:

(emphasis mine) (强调我的)

 attr(optional) using namespace nested-name-specifier(optional) namespace-name;

nested-name-specifier - a sequence of names and scope resolution operators::, ending with a scope resolution operator.嵌套名称说明符 - 名称序列和 scope 解析运算符::,以 scope 解析运算符结尾。 A single:: refers to the global namespace .单个:: 指的是全局命名空间

using namespace::std is the same as using namespace std; using namespace::stdusing namespace std;

The :: symbol is the scope resolution operator. ::符号是 scope 分辨率运算符。 When used without a scope name before it, it refers to the global namespace.当在其前面没有 scope 名称使用时,它指的是全局命名空间。 This means that std is a top level namespace, and is not enclosed in another.这意味着std是顶级名称空间,并且没有包含在另一个名称空间中。

For example, all of the following are valid:例如,以下所有内容都是有效的:

namespace A { namespace std{} }
using namespace::std;
using namespace A;
using namespace ::A;
using namespace::A;
using namespace A::std;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM