[英]c++ array syntax (function returns array)
Why does this code require the '&' in array syntax? 为什么这段代码需要数组语法中的'&'?
int (&returnArray(int (&arr)[42]))[42]
{
return arr;
}
When i declare it like this 当我宣布这样的时候
int (returnArray(int arr[42]))[42]
{
return arr;
}
i get 我明白了
error C2090: function returns array
But isn't this an array it was returning in the first example? 但这不是第一个例子中返回的数组吗? Was it some sort of a reference to array?
它是某种对数组的引用吗?
I know i can also pass an array to a function, where it will decay to a pointer 我知道我也可以将一个数组传递给一个函数,它会衰减到一个指针
int returnInt(int arr[42])
{
return arr[0];
}
or pass it by reference 或通过引用传递它
int returnInt(int (&arr)[42])
{
return arr[0];
}
But why can't i return an array the same way it can be passed? 但为什么我不能以相同的方式返回数组?
int (&returnArray(int (&arr)[42]))[42]
The first &
means this would return a reference to the array. 第一个
&
表示这将返回对数组的引用 。
This is required by the standard : 这是标准要求:
8.3.5 Functions §6 -
8.3.5功能§6 -
« Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things.
« 函数不应具有类型数组或函数的返回类型 ,尽管它们可能具有类型指针的返回类型或对此类事物的引用。 »
»
The first function is not returning an array, it's returning a reference to an array. 第一个函数不返回数组,它返回对数组的引用 。 Arrays cannot be returned by value in C++.
在C ++中,数组不能返回数组。
These topics are generally well covered in good C++ books . 这些主题通常都包含在优秀的C ++书籍中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.