C ++函数返回对数组的引用 [英] C++ function returning reference to array

查看:90
本文介绍了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 ++函数返回对数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆