8

不允许将命名空间和同名的类放在一个声明区域中,即

namespace A {}
class A{};

格式不正确(见 §3.3.1/4)。但是,可以通过 using-directive 引入任一名称:

namespace N { namespace A {int i;} }

struct A {static int i;};

using namespace N;

int i = A::i; // The global struct, or namespace N::A?

这段代码格式不正确吗?VC++和Clang都这么认为

main.cpp:7:9: error: reference to 'A' is ambiguous
int i = A::i;
        ^
main.cpp:3:8: note: candidate found by name lookup is 'A'
struct A {static int i;};
       ^
main.cpp:1:25: note: candidate found by name lookup is 'N::A'
namespace N { namespace A {int i;} }
                        ^

但是,GCC 接受它

谁是对的?

4

1 回答 1

8

代码格式不正确。查找时A,§7.3.4/6 进入:

如果名称查找在两个不同的命名空间中找到一个名称的声明,并且这些声明没有声明相同的实体并且没有声明函数,则该名称的使用是错误的。

这里,命名空间是全局命名空间和N,实体是命名空间N::A和类::A

于 2015-04-26T21:48:22.390 回答