I'm using vs2022 and I'm confused about the c++ post-decrement operator overloading value passing, why does overloading a function that returns a value instead of a reference also affect the object itself?
I tried to return a reference, aka MyInteger& operator--(int), and the output is consistent with a value return, both changing the value of the object itself. Why does the post-decrement operator have to return a value instead of a reference, and why does returning a value also change the value of the object itself?
#include <iostream>
using namespace std;
class MyInteger {
friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
MyInteger() {
m_int = 0;
}
MyInteger& operator--() {
m_int--;
return *this;
}
MyInteger operator--(int) {
MyInteger myint = *this;
//myint = *this;
m_int--;
return myint;
}
private:
int m_int;
};
ostream& operator<<(ostream& cout, MyInteger myint) {
cout << myint.m_int;
return cout;
}
void test() {
MyInteger myint;
cout << myint << endl;
cout << --myint << endl;
cout << myint << endl;
cout << myint-- << endl;
cout << (myint--)-- << endl;
cout << myint << endl;
}
int main()
{
test();
system("pause");
system("cls");
return 0;
}