zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    挑战程序设计竞赛第二章、贪心部分
    Life is Strange:《奇异人生》
    算法竞赛进阶指南第二章--题解
    算法竞赛进阶指南第一章题解
    2018 IEEE极限编程大赛 题解
    爬格子呀9.17(图论)
    大数模板(加减乘除幂次开方)
    地理位置(Geolocation)API 简介
    javascript闭包的理解
    H5本地离线存储
  • 原文地址:https://www.cnblogs.com/chenkkkabc/p/3240748.html
Copyright © 2011-2022 走看看