为什么要返回引用

来源:互联网 发布:英雄联盟for mac 国服 编辑:程序博客网 时间:2024/05/24 03:17

一个例子,来自《Effective C++》

class text{    public:    const char& operator[](std::size+_t positon)const    { return text[position];}    const char& operator[](std::size+_t positon)    { return text[position];}    private:    std::string txt;}text tb("hello");std::cout<<tb[0];tb[0]='x';text ctb("world");ctd::cout << ctb[0];ctb[0] = 'x';           //调用非const重载;如果重载【】返回的是非引用,那就是值传递的方式,//即其实是tb[0]的副本,tb[0]不会被更改
原创粉丝点击