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

标签 c++ visual-studio-2010 gcc

很简单,请看这段代码:

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/

相关文章:

c++ - 将 std::string 编码/解码为 UTF-16

C++ 存储大量 map 坐标的最佳文件格式

add-in - Fogbugz 的 VS 2010 插件?

visual-studio-2010 - 安装后 Git Extensions 没有出现在 VS 2010 中

visual-studio - 将 Visual Studio 2010 Professional 连接到 TFS

c - 在 x86_64 linux 中重定位超过 2GB 的程序时出现链接器错误?

c++ - 神秘的编译器错误,可能与使用 "virtual"有关?

c++ - 基于 CRTP 的解决方案会是什么样子?

c++ - gcc vector 扩展中的未对齐加载/存储

使用现代编译器编译的 C++ 项目,但链接到过时的 libstdc++