从函数传递/返回数组(非指针)引用的一般规则?

Naw*_*waz 33 c++ arrays compile-time

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

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

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

或者甚至更好,我们可以编写一个函数模板:

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
Run Code Online (Sandbox Code Playgroud)

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

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

int a[N];
int a[M][N];
int (*a)[N];
int (*a)[M][N];
Run Code Online (Sandbox Code Playgroud)

其中,MN在编译时已知!

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

编辑:

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

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

sth*_*sth 45

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

// an array
int global[10];

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

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

int (&variable)[1][2];
int (&functionA())[1][2];
int (&functionB(int param))[1][2];
Run Code Online (Sandbox Code Playgroud)

使用typedef可以使这些声明更加清晰:

typedef int array_t[10];

array_t& f() {
   return global;
}
Run Code Online (Sandbox Code Playgroud)

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

template<int N, int M>
int (&f(int (&param)[M][N]))[M][N] {
   return param;
}
Run Code Online (Sandbox Code Playgroud)

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


Tho*_*ing 10

使用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.
}
Run Code Online (Sandbox Code Playgroud)

  • 它返回对三个元素的int数组的引用. (2认同)

Eri*_*rik 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.
Run Code Online (Sandbox Code Playgroud)

  • @Nawaz:玩得开心.现在请输入dede这让我头痛:P (2认同)