路过的一般规则/从函数返回数组引用(没有指针)/? [英] General rules of passing/returning reference of array (not pointer) to/from a function?
问题描述
我们可以传递一个数组引用的函数,如:
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?
我想从一个函数返回folllowing类型的数组:
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];
其中, M
和 N
在编译时已知!
什么是一个数组的传递和返回编译时引用,并从功能的一般规则是什么?我们如何可以通过键入 INT(*一)[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?
编辑:
亚当评论: INT(*一)[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 (¶m)[M][N]))[M][N] {
return param;
}
的指针的到阵列的工作是相同的,只是他们使用 *
而不是&安培;
。
Pointers to arrays work the same, only that they use *
instead of &
.
这篇关于路过的一般规则/从函数返回数组引用(没有指针)/?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!