代码如下:
class MyInt {
//友元保证<<重载可行
friend ostream& operator<<(ostream& out, MyInt m);
public:
MyInt() {
num = 0;
}
// 前置++
//这里使用引用保证原来要修改的对象修改了
//不使用引用会返回一个修改后的新对象而不是原对象的修改
MyInt& operator++() {
// 先++
num++;
// 返回自身
return *this;
}
//使用占位参数解决前后++函数一致的问题
// 后置++
//这里不能使用引用
//因为temp是创建在堆中的临时变量,如果返回引用函数结束该临时对象就被销毁
//此时返回引用会导致不可用
MyInt operator++(int) {
// 先记录原来的值
MyInt temp = *this;
num++;
return temp;
}
private:
int num;
};
//写在类外的重载<<
ostream& operator<<(ostream& out, MyInt m) {
out << m.num;
return out;
}
// 递增运算符重载 ++
int main() {
MyInt m;
//前置++
//cout << ++(++m) << endl; // 1
//cout << m << endl; // 1
cout << m++ << endl; // 0
cout << m << endl; // 1
//int a = 0;
//cout << a++ << endl; // 0
//cout << a << endl; // 1
//cout << ++a << endl; // 2
//cout << a << endl; // 2
return 0;
}
几个关键问题:
1.使用占位参数解决前置++重载函数和后置++重载函数一致的问题。
前置++重载函数
MyInt& operator++() {
// 先++
num++;
// 返回自身
return *this;
}
后置++重载函数
MyInt operator++(int) {
// 先记录原来的值
MyInt temp = *this;
num++;
return temp;
}
2.二者返回值的区别:前置++重载函数使用引用返回是为了保证应该修改的对象修改了。而后置++重载函数在函数体内创建了一个临时对象temp,出函数体立刻销毁temp,返回temp的引用会出错,因此不能返回引用而返回一个temp的拷贝
3.重载<<函数第二个参数不使用引用是为了兼容后置++重载函数。