解释从函数中通过引用返回数组的语法

Explain syntax for returning array by reference from a function

C++中函数的语法是:

return_type function_name(parameter1, parameter2, ...)
{
    // function body
}

我对"returning reference of an array from a function"有一些疑问:

  1. Return 首先指定类型,然后指定函数名,但对于数组的 return 引用,它被写为:

    // for array of size 10
    int (&f())[10] {
       return global;
    }        
    

    为什么?

  2. 可以这样写吗:

    // return type followed by function name
    int&[10] f(){
       return global;
    }
    

    或类似的东西(没有 typedef)?

  3. 我无法理解 typedef 的用法,例如:

    typedef int array_t[10];
    array_t& f() {
       return global;
    }
    

    上面的代码将如何简化?简化后的代码会像第 1 点中的代码吗?

  1. why?

因为 Dennis Ritchie 在 C 中设计的如此,并且因为 C++ 被设计为与 C 兼容。

当然 C 中没有引用,但引用遵循与指针相同的语法规则,这些规则是从 C 继承的。

然而,主要的混淆似乎不是关于引用标点符号的位置,而是关于数组语法。数组大小总是位于名称的右侧。同样的模式也适用于变量:

int arr[size];
|   |  |
|   |  size
|   name
element type

int (&arr_ref)[size];
|     |       |
|     |       size
|     name
element type

int (&f())[10]
|     |   |
|     |   size
|     name
element type

函数声明的不同之处仅在于它具有参数列表。总是紧跟在名字之后。因为它紧跟在名称之后,所以它在数组大小之前。

  1. Can it be written as below:

没有。这在 C++ 中是错误的。

  1. I couldn't understand typedef usage when using it like:

typedef 只是一个别名;类型的不同名称。

how will the this code be simplified?

3.中的代码最简单。就个人而言,我更喜欢类型别名的 using 语法而不是 typedef:

using array_t = int[10];

另一种选择是使用尾随 return 类型,尽管这是否更简单是主观的:

auto f() -> int(&)[10] {

and will it look like the code in point 1?

声明看起来不同,但它声明了相同的功能。