在c语言中,数组作为函数参数时,实际上数组已经退化为指针使用。
下面这三种用法是等价的:
int f1(int apples[]);
int f1(int apples[10]);
int f1(int* apples);
这样一来,在f1中是无法知道数组的大小的,开发者必须提前知道数组大小。
C++中定义了数组的引用(例如,int (&a)[2]),可以有效的防止数组退化。
也就是,数组作为函数参数传递过去后,仍然是一个数组。
举例说明其用法
#include <iostream>
using namespace std;
int f1(int (&a)[6])
{
int count = 0;
for(int i=0; i < 6; i++)
{
count += a[i];
}
return count;
}
int main()
{
int apples[6] = {2,3,4,5,6,7};
int count = f1(apples);
cout<<"count:"<<count<<endl;
return 0;
}
如果将
int apples[6] = {2,3,4,5,6,7};
改为
int apples[5] = {2,3,4,5,6};
编译时将报错
$ g++ array_ref.cpp -o array_ref
array_ref.cpp: In function ‘int main()’:
array_ref.cpp:24: error: invalid initialization of reference of type ‘int (&)[6]’ from expression of type ‘int [5]’
array_ref.cpp:7: error: in passing argument 1 of ‘int f1(int (&)[6])’
说明编译时将进行数组长度的检查。
参考
http://www.cppblog.com/walkspeed/archive/2007/03/10/19525.aspx
http://blog.csdn.net/jiangxinyu/article/details/7767065
另外不可以定义引用的数组array of reference。
想定义类似这种
string& array[6] = {};
编译时报错
error: declaration of ‘array’ as array of references
There shall be no references to references, no arrays of references, and no pointers to references.
References are not objects. They don’t have storage of their own, they just reference existing objects. For this reason it doesn’t make sense to have arrays of references.
参考
http://stackoverflow.com/questions/1164266/why-are-arrays-of-references-illegal