前缀++与后缀++的重载

4.2 Item M6:自增(increment)、自减(decrement)操作符前缀形式与后缀形式的区别
不论是 increment 或 decrement 的前缀还是后缀都只有一个参数。为了解决这个语言问题,C++
规定后缀形式有一个 int 类型参数,当函数被调用时,编译器传递一个 0 做为 int 参数的值
给该函数

 

  1 #include <iostream>
  2 
  3 class UInt{
  4 public:
  5     explicit UInt(int i = 0) : m_int(i) { }
  6     ~UInt() { }
  7     UInt(const UInt &rhs) : m_int(rhs.get()) { }
  8 
  9 public:
 10     UInt &operator=(const UInt &rhs);
 11 
 12     //前缀形式返回一个引用,是一个左值
 13     //后缀形式返回一个const类型,是一个右值,亦即是不能被赋值
 14     UInt &operator++();
 15     const UInt operator++(int);
 16     UInt &operator--();
 17     const UInt operator--(int);
 18     UInt& operator+=(int);
 19     int get(void) const { return m_int; }
 20     void set(int i) { m_int = i; }
 21 private:
 22     int m_int;
 23 };
 24 
 25 UInt operator +(const UInt &lhs, const UInt &rhs)
 26 {
 27     UInt result;
 28 
 29     result.set(lhs.get() + rhs.get());
 30 
 31     return result;
 32 }
 33 
 34 UInt& UInt::operator =(const UInt &rhs)
 35 {
 36     m_int = rhs.get();
 37 
 38     return *this;
 39 }
 40 
 41 //返回一个自身的引用,没有临时对象的代价,性能较高
 42 UInt& UInt::operator ++()
 43 {
 44     *this += 1;
 45 
 46     return *this;
 47 }
 48 
 49 //返回一个临时对象,增加了一个对象构造和析构的代价,性能较低
 50 //由此可见,对于用户自定义类型,应该尽量使用前缀的increment
 51 const UInt UInt::operator ++(int)
 52 {
 53     UInt oldVal = *this;
 54 
 55     ++(*this);
 56 
 57     return oldVal;
 58 }
 59 
 60 UInt& UInt::operator --()
 61 {
 62     *this += (-1);
 63     
 64     return *this;
 65 }
 66 
 67 const UInt UInt::operator --(int)
 68 {
 69     UInt oldVal = *this;
 70 
 71     --(*this);
 72 
 73     return oldVal;
 74 }
 75 
 76 UInt& UInt::operator +=(int val)
 77 {
 78     m_int += val;
 79 
 80     return *this;
 81 }
 82 
 83 int main(void)
 84 {
 85     std::cout << "Hello World!" << std::endl;
 86 
 87     UInt u1(2);
 88     UInt u2(2);
 89 
 90     //Output 2
 91     std::cout << "u1++ return " << (u1++).get() << std::endl;
 92     //Output 3
 93     std::cout << "++u2 return " << (++u2).get() << std::endl;
 94 
 95     //Output 3
 96     std::cout << u1.get() << std::endl;
 97     //Output 3
 98     std::cout << u2.get() << std::endl;
 99 
100     return 0;
101 }

 

posted @ 2013-01-05 17:59  Jojodru  阅读(2843)  评论(0编辑  收藏  举报