自增(自减)的前后缀操作符由于没有带参数,所以重载的时候要区别开来处理,具体的做法是给后缀操作符号一个int 型的形参,这样编译器会自动传递实参0过去。
实现的原则是一切向int看齐
class UPInt { // "unlimited precision int"
public:
UPInt& operator++(); // prefix ++
const UPInt operator++(int); // postfix ++
UPInt& operator--(); // prefix --
const UPInt operator--(int); // postfix --
UPInt& operator+=(int); // a += operator for UPInts
// and ints
...
};
UPInt i;
++i; // calls i.operator++();
i++; // calls i.operator++(0);
--i; // calls i.operator--();
i--; // calls i.operator--(0);
既然引用被定义成一个左值,这就允许一个很特殊的习惯,那就是在完成某任务时,可以将对函数的调用放在=的左手边
实现++i的时候要返回引用类型,这样就++i=0;就有正确的结果
// prefix form: increment and fetch
UPInt& UPInt::operator++()
{
*this += 1; // increment
return *this; // fetch
}
实现i++的时候要调用++i的实现,利于代码的维护,要注意的是需要定义一个对象获取oldvalue并返回
返回const 是为了确保i++++这种操作会报错
// postfix form: fetch and increment
const UPInt UPInt::operator++(int)
{
UPInt oldValue = *this; // fetch
++(*this); // increment
return oldValue; // return what was
} // fetched