2009年1月31日

C++ Operator overloaded

Operator overloaded是C++獨特的功能,能夠把operator重新定義,符合class的需求,但是在定義的時候要注意是否違反class原本的意義。

  • Rule of thumb, if a class needs a destructor, it will also need the assignment  operator and a copy constructor. C++ Primer P.485
  • If the operator often does the same work, the common work should be put in private utility functions.
  1. #include <iostream>
  2. #include <cstdlib>
  3. using namespace std;
  4. //////////////////////////////////////////////////////
  5. class Point{
  6. public:
  7.     //constructor
  8.     Point(double xval=0.0, double yval=0.0):
  9.         x(xval), y(yval){}
  10.  
  11.     //copy constructor
  12.     Point(const Point &rhs):
  13.         x(rhs.x), y(rhs.y){}
  14.  
  15.     //destructor
  16.     ~Point(){}
  17.  
  18.     //must return a new object
  19.     friend Point
  20.     operator+ (const Point &lhs, const Point &rhs){
  21.         Point ret(lhs);
  22.         //call overloaded operator +=
  23.         ret += rhs;
  24.         return ret;
  25.     }
  26.  
  27.     //must return reference
  28.     Point& operator+= (const Point &rhs){
  29.         this->x += rhs.x;
  30.         this->y += rhs.y;
  31.         return *this;
  32.     }
  33.  
  34.     //prefix operator,return a reference
  35.     Point& operator++ (){
  36.         this->x += 1.0;
  37.         this->y += 1.0;
  38.         return *this;
  39.     }
  40.  
  41.     //posfix operator++, return a new object
  42.     Point operator++(int){
  43.         Point ret(*this);
  44.         ++*this;
  45.         return ret;
  46.     }
  47.  
  48.     friend inline bool
  49.     operator== (const Point &lhs, const Point &rhs){
  50.         return lhs.x == rhs.x && lhs.y == rhs.y;
  51.     }
  52.  
  53.     friend inline bool
  54.     operator!= (const Point &lhs, const Point &rhs){
  55.         return !(lhs == rhs);
  56.     }
  57.  
  58.     //input operators must deal with errors and EOF
  59.     friend istream&
  60.     operator>> (istream &in, Point &obj){
  61.         in>>obj.x>>obj.y;
  62.         if(!in)
  63.             obj = Point();
  64.         return in;
  65.     }
  66.  
  67.     //IO operators must be nomember functions
  68.     //should not print a newline
  69.     friend ostream&
  70.     operator<< (ostream &os, const Point &obj){
  71.         os<<"("<<obj.x<<", "<<obj.y<<")";
  72.         return os;
  73.     }
  74.  
  75. private:
  76.     double x, y;
  77. };
  78. //////////////////////////////////////////////////////
  79.