学习后置递增运算符重载时遇到问题,先看错误代码:
#include<iostream>
using namespace std;
class MyInteger {
friend ostream& operator<<(ostream& cout, MyInteger& myint);//全局函数做友元
public:
MyInteger() {
m_Num = 0;
}
//重载后置++运算符
MyInteger operator++(int) {
//先 记录当时结果
MyInteger temp = *this;
//后 递增
m_Num++;
//最后 将记录结果做返回
return temp;
}
private:
int m_Num;
};
//先重载<<运算符
ostream& operator<<(ostream& cout, MyInteger& myint) {
cout << myint.m_Num;
return cout;
}
void test01() {
MyInteger myint;
cout << myint++ << endl;
}
int main() {
test01();
system("pause");
return 0;
}
报错:
解决方法1:“重载<<运算符” 函数参数添加const,同时注意修改类中的友元定义。
//先重载<<运算符
ostream& operator<<(ostream& cout, const MyInteger& myint) {
cout << myint.m_Num;
return cout;
}
解决方法2:“重载<<运算符” 函数参数去掉引用符&,同时注意修改类中的友元定义。
//先重载<<运算符
ostream& operator<<(ostream& cout, MyInteger myint) {
cout << myint.m_Num;
return cout;
}
原因我猜测是由于本程序的目的是要修改myint的值,编译器为了防止“重载<<运算符”修改原本的myint值,运行时设限,所以要么加const禁止在“重载<<运算符”修改原本的值;要么就不用引用符&重新开辟内存,存储形参。编译器Visual Studio 2022。
这原因只是我的一些猜想,具体原因欢迎各位大佬批评指正,感谢!