为什么这段代码不能用VS2010和gcc 4.8.1编译

Khu*_*hid 3 c++ gcc visual-studio-2010

很简单,看看这段代码:

namespace B
{

    struct A{ int i; } ;

    A getA(int i);
}

//        ____ if I'll delete '::' then program successfull compiled.
//       /
::B::A  ::B::getA(int i){ ::B::A a = {i}; return a;}

#include <cstdio>
int main()
{

  ::B::A a = ::B::getA(2);

  printf("%d\n", a.i);

}
Run Code Online (Sandbox Code Playgroud)

错误列表VS2010:

1>main.cpp(94): error C3083: 'B': the symbol to the left of a '::' must be a type
1>main.cpp(94): error C2039: 'getA' : is not a member of 'B::A'
1>main.cpp(88) : see declaration of 'B::A'
1>error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>main.cpp(94): error C2440: 'return' : cannot convert from 'B::A' to 'int'
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>main.cpp(94): error C2617: 'getA' : inconsistent return statement
1>main.cpp(94) : see declaration of 'getA'
Run Code Online (Sandbox Code Playgroud)

Gcc.4.8.1错误列表(来自ideone.com):

   prog.cpp:10:1: error: ‘B’ in ‘struct B::A’ does not name a type
 ::B::A  ::B::getA(int i){ ::B::A a = {i}; return a;}
 ^
Run Code Online (Sandbox Code Playgroud)

问:这是一个错误,或者我不明白什么?

Mik*_*our 8

通常,除了需要分隔令牌之外,令牌之间的空格没有任何意义.所以这:

::B::A  ::B::getA(...)
Run Code Online (Sandbox Code Playgroud)

相当于

::B::A::B::getA(...)
Run Code Online (Sandbox Code Playgroud)

要指示它们是两个单独的限定名称,请在函数名称周围使用括号:

::B::A (::B::getA)(...)
Run Code Online (Sandbox Code Playgroud)

或者,正如您所说,删除顶级限定符(尽管如果您B在范围中调用了其他内容,则可能会导致混淆).