c++ - 在函数返回值中定义新类型

标签 c++ visual-c++

我惊讶地发现以下代码在 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/

相关文章:

c++ - 发送套接字结果 0x000000be

c++ - 如果 stdin 被另一个进程的管道替换,则 std::getline 中断

c++ - 使用隐式转换而不是 QueryInterface() 进行向上转换是否合法且具有多重继承?

c++ - 操作 c=a+++b 是什么意思?

c++ - 内存泄漏问题

c++ - 虚函数实现缺少类型说明符

c++ - 宏变量参数

C++ 可变数量的参数

c++ - cmake - CMakeLists.txt 不在根文件夹中(但包含在源代码中)

c++ - 事务中的sqlite3_step(stmt)失败,错误5,而没有调用我的忙处理程序