函数返回引用的含义

The function call expression is an lvalue to the referent.

When a function returns a reference, the function call becomes an lvalue for the referent. This is normally used to allow operator expressions (such as the subscript operator, the dereference operator, and so on) to be used as lvalues. The following example shows how returning a reference allows a subscript operator to be an lvalue.

#include <iostream>
#include <stdexcept>
using namespace std;

class Array {
public:
  float& operator[] (unsigned i) throw(out_of_range);
protected:
  float data_[100];
};

inline float& Array::operator[] (unsigned i)
throw(out_of_range)
{
  if (i >= 100u)
    throw out_of_range(" Array index is out of range");
  return data_[i];
}
int main()
{
  Array a;
  for (unsigned i = 0; i < 100; ++i)
    a[i] = 3.14 * i;
  for (unsigned j = 0; j < 100; ++j)
    cout << a[j] << '/n';
}

Returning a reference to data_[i] doesn't return a copy of data_[i]; it returns data_[i] itself. Therefore, anything done to the expression in the caller (a[i]) is actually done to data_[i]. In the example, the statement a[i] =...actually changes data_[i] within object a.

C programmers should note that this allows a function call to appear on the left side of an assignment operator.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值