如何从 C++ 中的函数 Return 复杂数据类型?

How to Return complex datatypes from functions in C++?

我们如何return 复杂的数据类型,例如从函数指向 int 数组的指针?

考虑下面的(非编译)代码:

int (*) [50] fcreate() 
{
    int (*p) [50]= new int[60][50];
    return p;
}

为什么它不起作用?

Error:
Expected un-qualified id before '(' in :

int (*) [50] fcreate();

一个解决方案是首先用现代语法表达函数:

auto fcreate()
    -> int (*)[50]
{ return new int[60][50]; }

auto main()
    -> int
{
    int x = fcreate;    // This won't compile: diagnostic shows syntax for you.
}

然后,当您编译此 x 声明的诊断时,会告诉您声明该函数的旧式语法:

foo.cpp:8:13: error: invalid conversion from 'int (* (*)())[50]' to 'int'

即使用旧语法,您可以将此函数定义为

int (*(fcreate)())[50]
{
    return new int[60][50];
}

也就是说,通常使用 std::vector 是个更好的主意。

或者用 std::vector 定义的矩阵 class 用于内部存储。


旧的语法声明看起来很丑陋,虽然它易于分析,但很难综合。可以通过为数组项类型定义名称来简化它。像这样:

using Array_item = int[50];

Array_item* fcreate()
{
    return new int[60][50];
}

您可以使用 C++03 typedef.

而不是 using

但是对于现代更清晰的尾随 return 类型语法,此解决方法的优势较小。

正确的语法如下:

int (*fcreate()) [50] {
    int (*p) [50]= new int[60][50];
    return p;
}

或者您可以使用中间别名:

template <typename T, size_t N>
using raw_array = T[N];

raw_array<int, 50>* fcreate() {
  int (*p) [50]= new int[60][50];
  return p;
}

但是如果您想要一个二维矩阵,并且第二个维度的大小固定,您宁愿结合使用 std::vectorstd::array

auto fcreate() {
    return std::vector<std::array<int, 50>>{};
}