使用命名空间std;并包括? [英] Ordering of using namespace std; and includes?
问题描述
我最近看到这个代码正在C ++项目的源文件中使用:
I recently saw this code being used in a source file in a C++ project:
using namespace std;
#include <iostream>
忽略所有问题:是否使用命名空间std 根本就是上面的代码甚至是合法的吗?在这两行之前,文件中没有代码。
Ignoring all issues of whether it's a good idea to have using namespace std
at all, is the above code even legal? There is no code in the file before these two lines.
我认为这不会编译,因为 namespace std
尚未在范围内声明,直到 #include
指令将它包含到文件中,但使用编译系统为该项目编译正好。如果有人有一个指向相关部分的链接,这将是最感激。
I would have thought that this wouldn't compile, since namespace std
hasn't been declared in scope until the #include <iostream>
directive includes it into the file, but using the build system for the project this was compiling just fine. If someone has a link to a relevant part of the spec, that would be most appreciated.
推荐答案
一个可能有趣的数据点。当我编译以下:
A perhaps interesting data point. When I compile the following:
using namespace std;
using namespace no_such_namespace;
使用g ++ 4.5.2,我得到:
with g++ 4.5.2, I get:
c.cpp:2:17: error: ‘no_such_namespace’ is not a namespace-name
c.cpp:2:34: error: expected namespace-name before ‘;’ token
std
code> no_such_namespace 在这一点上已经被定义为命名空间,但是g ++只抱怨第二个。我不会认为在没有声明的情况下,标识符 std
有什么特别的。我认为@James Kanze是对的,这是g ++中的错误。
Neither std
nor no_such_namespace
has been defined as a namespace at that point, but g++ complains only about the second. I don't think there's anything special about the identifier std
in the absence of a declaration of it. I think @James Kanze is right that this is a bug in g++.
编辑:并且已经被报告。(5年前!)
更新:现在超过8年,还没有被分配给任何人,更不用说固定。 g ++ 4.9.2会出现问题。 clang ++ 3.5没有,但它对 std
发出警告,并为 no_such_namespace
:
UPDATE: Now it's more than 8 years, and still hasn't been assigned to anyone, much less fixed. g++ 4.9.2 exhibits the problem. clang++ 3.5 doesn't, but it issues a warning for std
and a fatal error for no_such_namespace
:
c.cpp:1:17: warning: using directive refers to implicitly-defined namespace 'std'
using namespace std;
^
c.cpp:2:17: error: expected namespace name
using namespace no_such_namespace;
^
1 warning and 1 error generated.
这篇关于使用命名空间std;并包括?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!