C++重载自增/减操作符

作为类成员使用。

前缀是先加/减1,再取值;后缀是先取值,再加/减1。

前缀是左值,返回引用;后缀是右值,返回值。

后缀多一个int参数进行区分,用时编译器会传个没用的0作实参。

在后缀实现中调用前缀版本。

可以显式调用:前缀 xxx.operator++(); 后缀 xxx.operator++(0)

#include <iostream>
#include <stdexcept>

class CheckedPtr {
public:
  // no default ctor
  CheckedPtr(int* b, int *e) : beg(b), end(e), cur(b) {}
  // prefix operators
  CheckedPtr& operator++();
  CheckedPtr& operator--();
  // postfix operators
  CheckedPtr operator++(int);
  CheckedPtr operator--(int);
private:
  int* beg;
  int* end;
  int* cur;
};

CheckedPtr& CheckedPtr::operator++()
{
  if (cur == end) {
    throw std::out_of_range("increment past the end of CheckedPtr");
  }
  ++cur;
  return *this;
}

CheckedPtr& CheckedPtr::operator--()
{
  if (cur == beg) {
    throw std::out_of_range("decrement past the beginning of CheckedPtr");
  }
  --cur;
  return *this;
}

CheckedPtr CheckedPtr::operator++(int)
{
  CheckedPtr ret(*this);
  ++*this;
  return ret;
}

CheckedPtr CheckedPtr::operator--(int)
{
  CheckedPtr ret(*this);
  --*this;
  return ret;
}

int main()
{
  int ia[10];
  CheckedPtr parr(ia, ia+10);
  try {
    parr++;
    ++parr;
    parr.operator++(0);
    parr.operator++();
  }
  catch (const std::out_of_range& e) {
    std::cerr << e.what() << std::endl;
  }
  return 0;
}

 

posted on 2013-08-07 15:09  chenkkkabc  阅读(337)  评论(0编辑  收藏  举报