除了使用指针之外,还有其他方法可以从函数返回中接收对数组的引用吗?
这是我的代码。
int ia[] = {1, 2, 3};
decltype(ia) &foo() { // or, int (&foo())[3]
return ia;
}
int main() {
int *ip1 = foo(); // ok, and visit array by ip1[0] or *(ip1 + 0)
auto ip2 = foo(); // ok, the type of ip2 is int *
int ar[] = foo(); // error
int ar[3] = foo(); // error
return 0;
}
还有一个类版本。
class A {
public:
A() : ia{1, 2, 3} {}
int (&foo())[3]{ return ia; }
private:
int ia[3];
};
int main() {
A a;
auto i1 = a.foo(); // ok, type of i1 is int *, and visit array by i1[0]
int i2[3] = a.foo(); // error
return 0;
}
注意:代码中省略了 const
限定符。
我知道数组的名称是指向该数组中第一个元素的指针,因此使用指针接收是完全可行的。
对不起,我弄错了。来自 Array to pointer decay
There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array.
请无视XD
我只是对我一开始问的问题感到好奇:)
最佳答案
Is there any other way to receive a reference to an array from function returning except using a pointer?
是的,使用对数组的引用,就像任何其他类型一样:
int (&ref)[3] = a.foo();
为避免笨拙的语法,您可以改用 typedef
。
typedef int int_array3[3];
...
int_array3& foo() { return ia; }
...
int_array3& ref = a.foo();
关于C++ 函数返回对数组的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34439284/