很简单,请看这段代码:
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);
}
错误列表 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'
Gcc.4.8.1 错误列表(from 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;}
^
问:这是一个错误还是我不明白什么?
最佳答案
一般而言, token 之间的空格没有任何意义,除非需要它来分隔 token 。所以这个:
::B::A ::B::getA(...)
相当于
::B::A::B::getA(...)
要表明它们是两个独立的限定名,请在函数名两边使用括号:
::B::A (::B::getA)(...)
或者,如您所说,删除顶级限定符(尽管如果范围内还有其他名为 B
的东西,这可能会导致混淆)。
关于c++ - 为什么这段代码不能用 VS2010 和 gcc 4.8.1 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22461641/