Wednesday, May 22, 2013

C++ Operator Overloading


Assignment Operator
X& X::operator=(X rhs)
{
  swap(rhs);
  return *this;
}
Input and Output Operators
std::ostream& operator<<(std::ostream& os, const T& obj)
{
  // write obj to stream
  return os;
}
std::istream& operator>>(std::istream& is, T& obj)
{
  // read obj from stream
  if( /* no valid object of T found in stream */ )
    is.setstate(std::ios::failbit);
  return is;
}

Comparison operators
inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){return !operator==(lhs,rhs);}
inline bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator> (const X& lhs, const X& rhs){return  operator< (rhs,lhs);}
inline bool operator<=(const X& lhs, const X& rhs){return !operator> (lhs,rhs);}
inline bool operator>=(const X& lhs, const X& rhs){return !operator< (lhs,rhs);}
Arithmetic Operatorsclass X {
  X& operator++()
  {
    // do actual increment
    return *this;
  }
  X operator++(int)
  {
    X tmp(*this);
    operator++();
    return tmp;
  }
};
Binary arithmetic operators
class X {
  X& operator+=(const X& rhs)
  {
    // actual addition of rhs to *this
    return *this;
  }
};
inline X operator+(X lhs, const X& rhs)
{
  lhs += rhs;
  return lhs;
}
Array Subscription
class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
  // ...
};

Operators for Pointer-like Types
class my_ptr {
        value_type& operator*();
  const value_type& operator*() const;
        value_type* operator->();
  const value_type* operator->() const;
};



No comments:

Post a Comment