解释下标操作符为什么要返回引用

    重载下标操作符的一大好处便是对对象内部的容器可以像访问数组元素一样进行读写。

    如果重载的下标操作符不返回引用,便只能读取对象的内部状态。

#include <vector>
using std::vector;
#include <iostream>
using std::cout; using std::endl;

class Foo {
public:
Foo(): data(100) { for (int i = 0; i != 100; ++i) data[i] = i; }
    int operator[](const size_t);
    //const int operator[](const size_t) const;
    // other interface members
private:
    vector<int> data;
    // other member data and private utility functions
};

int Foo::operator[](const size_t index)
{
	return data[index];   // no range checking on index
}


int main() {
	
    Foo f;
    cout << f[50] << endl; //相当于cout << f.operator[](50) << endl;
    f[50] = 90;   //相当于f.operator[](50) = 90;
    cout << f[50] << endl;
    system("pause");
    return 0;
}
    这时候便会发现利用下标操作符只能读取data的i50号元素,但不可以修改,即不可以写。

    f[50]相当于调用了成员函数f.operator[](50),由于不是返回引用,那么函数在返回的地方会创建一个临时整形变量,并用f.data[50]进行初始化,所以即使可以赋值,也仅仅是对临时对象进行赋值。但如果该函数返回的是引用的话,那么函数调用结束后并不会创建临时变量保存运算结果,而是直接把f.data[50]放在调用结束处,因此是可以改写对象的内部状态的。这便是返回引用的好处。

  


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值