我惊讶地发现以下代码在 MSVC 下编译、运行并产生预期的输出:
#include <iostream>
using namespace std;
struct Foo{
int _x;
Foo(int x): _x(x) {}
} //Note: no semi-colon after class definition.
//Makes this behave as a return type for the following function:
Foo_factory(int x)
{return Foo(x);}
int main (int argc, char* argv[])
{
Foo foo = Foo_factory(42);
cout << foo._x << endl; //Prints "42"
return 0;
}
看到 MinGW 编译失败并出现错误“新类型可能未在返回类型中定义”,我并不感到惊讶。这只是标准的另一个 Microsoft 异常(exception),还是合法的 C++?
最佳答案
在 N3797 (C++14) 和 N3485 (C++11) 中,§8.3.5 [dcl.fct]/9 显式开始于:
Types shall not be defined in return or parameter types.
因此,您的代码无效,GCC 对其进行诊断是正确的。
关于c++ - 在函数返回值中定义新类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29609081/