C ++函数返回对数组的引用

编程入门 行业动态 更新时间:2024-10-23 12:26:28
本文介绍了C ++函数返回对数组的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

除了使用指针之外,还有其他方法可以从函数返回中接收对数组的引用吗?

Is there any other way to receive a reference to an array from function returning except using a pointer?

这是我的代码。

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 在代码中省略了限定符。

Note: const qualifier is omitted in code.

我知道数组的名称是指向该数组中第一个元素的指针,因此使用指针进行接收完全是可行。

对不起,我犯了一个错误。来自指向指针衰减的数组

Sorry, I made a mistake. From 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

我只是对刚开始问的问​​题很好奇:)

I'm just curious about the question I asked at the beginning :)

推荐答案

除了使用指针之外,还有其他方法可以从函数返回中接收对数组的引用?

Is there any other way to receive a reference to an array from function returning except using a pointer?

是,使用对数组的引用,就像其他类型一样:

Yes, using a reference to an array, like with any other type:

int (&ref)[3] = a.foo();

为避免笨拙的语法,可以使用 typedef

To avoid the clunky syntax, you could use a typedef instead.

typedef int int_array3[3]; ... int_array3& foo() { return ia; } ... int_array3& ref = a.foo();

更多推荐

C ++函数返回对数组的引用

本文发布于:2023-07-29 00:38:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235600.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!