向/从函数传递/返回数组(不是指针)的引用的一般规则? [英] General rules of passing/returning reference of array (not pointer) to/from a function?

查看:21
本文介绍了向/从函数传递/返回数组(不是指针)的引用的一般规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以将数组的引用传递给函数,例如:

We can pass reference of an array to a function like:

void f(int (&a)[5]);

int x[5];
f(x);     //okay
int y[6];
f(y);     //error - type of y is not `int (&)[5]`.

或者更好的是,我们可以写一个函数模板:

Or even better, we can write a function template:

template<size_t N>
void f(int (&a)[N]); //N is size of the array!

int x[5];
f(x);     //okay - N becomes 5
int y[6];
f(y);     //okay - N becomes 6

<小时>

现在我的问题是,如何从函数返回数组的引用?


Now my question is, how to return reference of an array from a function?

我想从函数返回以下类型的数组:

I want to return array of folllowing types from a function:

int a[N];
int a[M][N];
int (*a)[N];
int (*a)[M][N];

其中 MN 在编译时是已知的!

where M and N is known at compile time!

在函数之间传递和返回数组的编译时引用的一般规则是什么?我们如何将 int (*a)[M][N] 类型的数组的引用传递给函数?

What are general rules for passing and returning compile-time reference of an array to and from a function? How can we pass reference of an array of type int (*a)[M][N] to a function?

Adam 评论:int (*a)[N] 不是数组,而是指向数组的指针.

Adam commented : int (*a)[N] is not an array, it's a pointer to an array.

是的.但是一维在编译时是已知的!我们如何将这些在编译时已知的信息传递给函数?

Yes. But one dimension is known at compile time! How can we pass this information which is known at compile time, to a function?

推荐答案

如果你想从函数返回对数组的引用,声明应该是这样的:

If you want to return a reference to an array from a function, the declaration would look like this:

// an array
int global[10];

// function returning a reference to an array
int (&f())[10] {
   return global;
}

返回数组引用的函数声明看起来与作为数组引用的变量声明相同 - 只是函数名称后跟 (),即可能包含参数声明:

The declaration of a function returning a reference to an array looks the same as the declaration of a variable that is a reference to an array - only that the function name is followed by (), which may contain parameter declarations:

int (&variable)[1][2];
int (&functionA())[1][2];
int (&functionB(int param))[1][2];

使用 typedef 可以使此类声明更加清晰:

Such declarations can be made much clearer by using a typedef:

typedef int array_t[10];

array_t& f() {
   return global;
}

如果你想让它变得非常混乱,你可以声明一个函数,它接受对数组的引用并返回这样的引用:

If you want it to get really confusing, you can declare a function that takes a reference to an array and also returns such a reference:

template<int N, int M>
int (&f(int (&param)[M][N]))[M][N] {
   return param;
}

指向数组的指针的工作原理相同,只是它们使用 * 而不是 &.

Pointers to arrays work the same, only that they use * instead of &.

这篇关于向/从函数传递/返回数组(不是指针)的引用的一般规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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