C++中自增和自减操作符的重载

自增(自减)的前后缀操作符由于没有带参数,所以重载的时候要区别开来处理,具体的做法是给后缀操作符号一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值