35

我们可以将数组的引用传递给如下函数:

void f(int (&a)[5]);

int x[5];
f(x);     //okay
int y[6];
f(y);     //error - type of y is not `int (&)[5]`.

或者更好的是,我们可以写一个函数模板:

template<size_t N>
void f(int (&a)[N]); //N is size of the array!

int x[5];
f(x);     //okay - N becomes 5
int y[6];
f(y);     //okay - N becomes 6

现在我的问题是,如何从函数返回数组的引用?

我想从函数返回以下类型的数组:

int a[N];
int a[M][N];
int (*a)[N];
int (*a)[M][N];

在编译时在哪里M和是已知的!N

将数组的编译时引用传递给函数和从函数返回的一般规则是什么?我们如何将类型数组的引用传递int (*a)[M][N]给函数?

编辑:

Adam评论说:int (*a)[N]不是数组,它是指向数组的指针。

是的。但是一维在编译时是已知的!我们如何将这些在编译时已知的信息传递给函数?

4

6 回答 6

46

如果要从函数返回对数组的引用,则声明如下所示:

// an array
int global[10];

// function returning a reference to an array
int (&f())[10] {
   return global;
}

返回对数组的引用的函数的声明看起来与作为对数组的引用的变量的声明相同 - 只是函数名后面跟着(),它可能包含参数声明:

int (&variable)[1][2];
int (&functionA())[1][2];
int (&functionB(int param))[1][2];

使用 typedef 可以使此类声明更加清晰:

typedef int array_t[10];

array_t& f() {
   return global;
}

如果你想让它变得非常混乱,你可以声明一个函数,它接受一个数组的引用并返回这样的引用:

template<int N, int M>
int (&f(int (&param)[M][N]))[M][N] {
   return param;
}

指向数组的指针的工作方式相同,只是它们使用*而不是&.

于 2011-03-22T23:12:52.827 回答
12

使用 C++11 的尾随返回类型语法,您还可以编写:

auto foo () -> int (&)[3]
{
    static int some_array[3]; // doesn't have to be declared here
    return some_array; // return a reference to the array.
}
于 2014-08-06T20:04:47.187 回答
9

您不能从函数返回数组。

8.3.5/6:

函数不应具有类型数组或函数的返回类型,尽管它们可能具有类型指针或对此类事物的引用的返回类型。

编辑:你会喜欢语法:

int (&bar()) [5] {
  static int x[5];
  return x;
}


int (* & bar()) [6][10] {
    static int x[6][10];
    static int (*y)[6][10] = &x;
    return y;
}
// Note - this returns a reference to a pointer to a 2d array, not exactly what you wanted.
于 2011-03-22T23:07:42.300 回答
3

正如Erik 提到的,您不能从函数中返回数组。你可以返回一个指针或一个引用,尽管语法很复杂:

// foo returns a pointer to an array 10 of int
int (*foo(float arg1, char arg2))[10] { ... }

// bar returns a reference to an array 10 of int
int (&foo(float arg1, char arg2))[10] { ... }

我强烈建议为数组类型创建一个 typedef:

// IntArray10 is an alias for "array 10 of int"
typedef int IntArray10[10];

// Equivalent to the preceding definitions
IntArray10 *foo(float arg1, char arg2) { ... }
IntArray10 &bar(float arg1, char arg2) { ... }
于 2011-03-22T23:14:17.090 回答
1

对某事的好答案的补充,这里是如何用一个返回数组引用的常量方法声明一个类:

class MyClass
{
public:
    const int (&getIntArray() const)[10];
};
于 2016-01-27T13:41:55.257 回答
0

这被标记为 C++,所以我将建议在 C++ 中返回数组的方法是返回 astd::vector而不要尝试使用 C 数组的任何技巧(仅应在 C++ 代码中精心选择的场景中使用)。

正如其他答案所述,您不能从函数返回 C 数组。

于 2011-03-22T23:23:54.213 回答