学习递增运算符之后,自己写递减运算符,然后写完后置递减,发现一直报错然后查百度,发现是左移运算符需要加const
错误
解决办法
将const加入到左移的第二个参数,如果使用友元,同样添加;
// 友元
friend ostream &operator<<(ostream &cout, const MyInter(类名称) &p);
// 全局函数
ostream &operator<<(ostream &cout, const MyInter &p)
原因:使用cout为了不能改变类的属性,必须加const。
以下为修改后代码:
/*
author:ivarnd;
time:2022/8/21;
功能:重载递减运算符
*/
#include<iostream>
#include<string>
using namespace std;
class MyInter{
// 友元
friend ostream &operator<<(ostream &cout, const MyInter &p);
public:
MyInter()
{
m_int = 0;
}
/*
前置和后置的不同:
前置递增返回引用 后置递增返回值(temp是临时变量 用完就要被释放)
*/
// 前置递减
MyInter &operator--()
{
// 先进行++运算
m_int--;
// 在将自身返回
return *this;
}
// 后置递减返回值
// operator--(int), int代表占位符,用于区分前置递减和后置递减
MyInter operator--(int)
{
MyInter temp = *this; // 记录当前值
m_int--; // 进行递减操作
return temp; // 将记录结果做返回
}
private:
int m_int;
};
// 左移运算符
// 需要加入const
ostream &operator<<(ostream &cout, const MyInter &p)
{
cout << p.m_int;
return cout;
}
void test01()
{
MyInter myint;
cout << --myint << endl;
cout << myint << endl;
}
void test02()
{
MyInter myint;
cout << myint-- << endl;
cout << myint << endl;
}
int main()
{
test02();
return 0;
}