C++数组的引用—防止数组退化

在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 functionint main()’:
array_ref.cpp:24: error: invalid initialization of reference of typeint (&)[6]’ from expression of typeint [5]’
array_ref.cpp:7: error: in passing argument 1 ofint 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

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值