【问题标题】:Define a new type in a function return value在函数返回值中定义新类型
【发布时间】:2015-04-13 15:21:53
【问题描述】:

我惊讶地发现以下代码在 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 例外,还是合法的 C++?

【问题讨论】:

标签: c++ visual-c++


【解决方案1】:

在 N3797 (C++14) 和 N3485 (C++11) 中,§8.3.5 [dcl.fct]/9 明确以:

类型不应在返回或参数类型中定义。

因此,您的代码无效,而 GCC 可以正确诊断它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2011-01-03
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2022-06-16
    相关资源
    最近更新 更多