重载[]运算符,当作右值时不调用const成员函数

蓝猫淘气 蓝猫淘气 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
C++primer书上意思是做右值时自动调用const成员函数,但是实验看到结果还是调用重载的下标运算符的普通成员函数,返回引用。
如果调用下标运算符做右值时不调用const成员函数,而是普通成员函数,返回引用,那就会访问到私有成员变量,破坏封装性呀。

Primer.hpp
class CheckoutRecord{
friend ostream& operator<<(ostream&, const CheckoutRecord&);
friend istream& operator>>(istream&, CheckoutRecord&);
public:
typedef vector<pair<string, string>*>::size_type size_type;
CheckoutRecord(double d = 0,
string t = "NULL",
Date d1 = Date(),
Date d2 = Date()):
book_id(d), title(t), date_borrowed(d1), date_due(d2){}
pair<string, string>& operator[](size_type i);
const pair<string, string>& operator[](const size_t i) const;
private:
double book_id;
string title;
Date date_borrowed;
Date date_due;
pair<string, string> borrower;
vector<pair<string, string>*> wait_list;
};

Primer.cpp

const pair<string, string>&
CheckoutRecord::operator[](const size_t i) const{
cout << "const pair<string, string>& CheckoutRecord::operator[](size_t i)" << endl;
return *wait_list[i];
}

pair<string, string>&
CheckoutRecord::operator[](size_t i){
cout << "pair<string, string>& CheckoutRecord::operator[](size_t i)" << endl;
return *wait_list[i];
}


main.cpp

CheckoutRecord obj1;
readFile(obj1);
cout << obj1;
cout << obj1[2].first << "," << obj1[2].second << endl;
pair<string, string>* val = &obj1[1];
val->first = "hu";
cout << obj1 << endl;


结果

book_id:787001 title:cprimer, 2016-1-1, 2016-4-1, wang xin
li, shumeng
li, bo
pan, ji
zhu, xiantan
pair<string, string>& CheckoutRecord::operator[](size_t i)
pan,pair<string, string>& CheckoutRecord::operator[](size_t i)
ji
pair<string, string>& CheckoutRecord::operator[](size_t i)
book_id:787001 title:cprimer, 2016-1-1, 2016-4-1, wang xin
li, shumeng
hu, bo
pan, ji
zhu, xiantan

Program ended with exit code: 0
...全文

相关推荐

两个二维数组相加,用成员函数重载运算符“+”和“-”

用成员函数重载运算符“+”和“-”,将两个二维数组相加和相减。要求第一个二维数组的值由构造函数设置,另一个二维数组的值由键盘输入。

trouble0508

⚡【C++要笑着学】(8) 重载:运算符重载 | 赋值重载 (默认) | const 成员 | const 修饰成员函数 | 取地址重载 (默认) | const 取地址重载 (默认)

本章将开始讲解运算符重载。运算符重载的技能是学习实现STL 内部底层的不可缺少的 "利器" !所以本篇非常重要,下一篇会手把手实现一个Date类,可以进一步地实战体会运算符重载。

王平渊

C++运算符重载 成员函数与友元函数详解

代码如下:#include<iostream>using namespace std;class A{    int x,y;    public:    A(int xx,int yy):x(xx),y(yy){}    A(){x=0;y=0;}    A operator+(const A&b) //不加const限定,也可以    { return A(x+b.x,y+b.y); }    A operator-()    { return A(-x,-y); }    void show()    {cout&lt;&lt;“x=”&lt;&lt;x&lt;&lt;” y=”&lt;&lt;y&lt;&lt;endl;}};void test

weixin_38501751

复数类加减法运算符重载成员函数

通过控制台输入输出,DOS窗口,以复数类为例,通过运算符重载成员函数的方式,实现复数类的加减法运算

yangxiaoguai132

C++运算符重载友元函数实例

一个实例,实现运算符重载(成员函数和非成员函数两种方式),友元函数的使用,注意事项等,自己学习时编写的,

Kasen's experience
评论 7
收藏 已收藏
分享
返回顶部
蓝猫淘气
C++ 语言 65,212 成员 250,513 内容