除了使用指针之外,还有其他方法可以从函数返回接收对数组的引用吗?
这是我的代码.
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;
}
Run Code Online (Sandbox Code Playgroud)
和一个类版本.
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;
}
Run Code Online (Sandbox Code Playgroud)
注意:const代码中省略了限定符.
我知道数组的名称是指向该数组中第一个元素的指针,因此使用指针接收是完全可行的.
对不起,我搞错了.从Array到指针衰减
存在从数组类型的左值和右值到指针类型的右值的隐式转换:它构造指向数组的第一个元素的指针.
请忽略那个XD
我只是对我在开始时提出的问题感到好奇:)
jua*_*nza 13
除了使用指针之外,还有其他方法可以从函数返回接收对数组的引用吗?
是的,使用对数组的引用,与任何其他类型一样:
int (&ref)[3] = a.foo();
Run Code Online (Sandbox Code Playgroud)
为了避免使用笨重的语法,您可以使用typedef替代语法.
typedef int int_array3[3];
...
int_array3& foo() { return ia; }
...
int_array3& ref = a.foo();
Run Code Online (Sandbox Code Playgroud)
Sla*_*ica 11
您应该使用std :: array来避免混淆,并使代码更清晰,更安全,更少笨重:
class A {
public:
typedef std::array<int,3> array;
A() : ia{1, 2, 3} {}
array &foo(){ return ia; }
private:
array ia;
};
int main() {
A a;
auto i1 = a.foo(); // ok, type of i1 is A::array, it is a copy and visit array by i1[0]
for ( int i : i1 ) {} // you can iterate now, with C array you cannot anymore
auto &i2 = a.foo(); // ok, type of i2 is A::array&, you can change original by i2[0] = 123
A::array i3 = a.foo(); // fine, i3 is now a copy and visit array by i3[0]
A::array &i4 = a.foo(); // fine, you can change original by i4[0] = 123
int *i5 = a.foo().data(); // if you want old way to pass to c function for example, it is safer you explicitly show your intention
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道数组的名称是指向该数组中第一个元素的指针
这是不正确的,数组可以隐式转换为指向第一个元素的指针.它不一样.