在C++中返回数组引用的语法

Izo*_*ine 8 c++ arrays reference declaration function

当我遇到这个问题时,我一直在研究C++中的数组概念:用c ++返回一个数组

有人回答使用此声明:

int (&f(int (&arr)[3]))[3]
Run Code Online (Sandbox Code Playgroud)

我无法理解的是在结束括号后的[3].我从未见过看起来像这样的函数声明.我理解其余的语法,但我并不特别理解[3]是如何工作的,因为它位于函数名之后.如果我忽略了一些简单的事情,我会提前道歉.我也尝试查看函数声明的规范,但我没有看到任何可以链接到下标语法的相关内容.那么,这怎么可能呢?

Naw*_*waz 6

该函数返回对大小数组的引用,并且该函数实际上是要返回的数组大小作为参考.int3[3]

这种模糊的语法来自数组声明的奇怪语法,您可以这样做:

int arr[3]; //real but weird
Run Code Online (Sandbox Code Playgroud)

如果它有这样的语言会更简单:

int[3] arr; //hypothetical but better and simpler
Run Code Online (Sandbox Code Playgroud)

因为大小3是类型的一部分arr,所以如果所有部分都出现在变量名称的左侧,那就更有意义了,就像你写的时一样:

unsigned int a;
Run Code Online (Sandbox Code Playgroud)

你不写:

unsigned a int; //analogous to : int a [3];
Run Code Online (Sandbox Code Playgroud)

因此,尽管语言做得恰到好处unsigned int,但它确实非常奇怪int[3].

现在回到函数声明,如果将函数声明为:

int[3]& f(int[3]& arr); //hypothetical
Run Code Online (Sandbox Code Playgroud)

只有它的变量名左侧有所有部分.但是因为它没有这样做(即语言要求你在变量名后面的最右边写大小),你最终会得到这个奇怪的签名:

int (&f(int (&arr)[3])[3]; //real
Run Code Online (Sandbox Code Playgroud)

请注意,即使参数变得奇怪.


但您可以使用typedef简化它:

typedef int array_type[3];

array_type& f(array_type& arr);
Run Code Online (Sandbox Code Playgroud)

这看起来好多了.现在只有typedef看起来很怪异.

使用C++ 11,您甚至可以编写更好的typedef:

using array_type = int[3];

array_type& f(array_type& arr);
Run Code Online (Sandbox Code Playgroud)

这是如此接近(如果你想象array_typeint[3]):

int[3]& f(int[3]& arr); //hypothetical
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.