Possible Duplicate:
Confusion over C++ pointer and reference topic
假设我路过
int arr[10];
作为函数的参数。
这些都是有效的函数原型(prototype)吗?它们在论点方面有何不同?为什么?
这是我目前知道的(不确定是否正确)
1. void foo(int &arr); //a reference to an array, which preserve the size attribute?
2. void foo(int &arr[]); //the same (is it)?
3. void foo(int (&arr)[]); //I don't know
4. void foo(int &arr[10]); //is it the same as 2?
5. void foo(int (&arr)[10]);//no idea
6. void foo(int *arr); //a decayed pointer of the array, pointing to the first element of the array, losing the size attribute?
7. void foo(int *arr[]); //the same (is it?)
8. void foo(int (*arr)[]); //a pointer to an array, preserve the size
9. void foo(int *arr[10]); //the same as 7 (is it?)
10. void foo(int (*arr)[10]);//is the same as 8 (is it?)
11. void foo(int arr[]); //is the same as 6 (is it?)
12. void foo(int arr[10]); // is the same as 6 (is it?)
(我知道这需要一个冗长的解释,抱歉,我完全糊涂了...)
第一个重要信息是类型为T
的(有界或无界)数组的参数被转换为指向T
的指针。 IE。 int arr[]
和 int arr[10]
都被转换为 int * arr
。请注意,转换仅在顶级数组上执行,即它不会发生在 int (*arr)[10]
中,它是指向 int 数组的指针。
此外,标识符右边的东西比左边的东西绑定(bind)得更紧密,即 int *arr[10]
是一个数组,而 int (*arr)[10 ]
是一个指针。
最后,引用的数组和指向引用的指针是无效的,指向无界数组的指针和引用也是如此。
1. void foo(int &arr); // can't pass, reference to int
2. void foo(int &arr[]); // invalid, pointer to reference to int
3. void foo(int (&arr)[]); // invalid, reference to unbounded array of int
4. void foo(int &arr[10]); // invalid, pointer to reference to int
5. void foo(int (&arr)[10]); // can pass, reference to an array of int
6. void foo(int *arr); // can pass, pointer to int
7. void foo(int *arr[]); // can't pass, pointer to pointer to int
8. void foo(int (*arr)[]); // invalid, pointer to an unbounded array of int.
9. void foo(int *arr[10]); // can't pass, pointer to pointer to int
10. void foo(int (*arr)[10]); // can't pass, pointer to array of int
11. void foo(int arr[]); // can pass, pointer to int
12. void foo(int arr[10]); // can pass, same as above
使用 arr
作为 foo
的参数将导致它衰减到指向其第一个元素的指针——传递给 foo
的值将是 int *
类型。请注意,您可以将 &arr
传递给数字 10,在这种情况下,将传递 int (*)[10]
类型的值,并且不会发生衰减。