码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 双目运算符重载

时间:2018-08-25 11:37:42      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:color   this   pre   hat   +=   amp   c++   调用   operator   

  1 class Point
  2 {
  3     int x;
  4     int y;
  5 public:
  6     //Point(void) { }
  7     Point(int _x=0,int _y=0)
  8     {
  9         x = _x;
 10         y = _y;
 11     }
 12     
 13     Point(Point& that)
 14     {
 15         x = that.x;
 16         y = that.y;
 17     }
 18     
 19     Point operator + (Point& that)
 20     {
 21         Point t;//此行代码会调用无参构造
 22         t.x = x + that.x;
 23         t.y = y + that.y;
 24         return t;
 25     }
 26     
 27     Point operator += (Point& that)
 28     {
 29         x = x + that.x;
 30         y = y + that.y;
 31         return *this;
 32     }
 33     
 34     Point operator * (Point& that)
 35     {
 36         Point t;
 37         t.x = x * that.x;
 38         t.y = y * that.y;
 39         return t;
 40     }
 41     
 42     Point operator ++ (int)
 43     {
 44         Point t(*    this);//此行代码会调用无参构造
 45         x++;
 46         y++;
 47         return t;
 48     }
 49 
 50     Point operator ++ ()
 51     {
 52         x++;
 53         y++;
 54         return *this;
 55     }
 56     
 57     Point* operator -> (void)
 58     {
 59         return this;
 60     }
 61     
 62     friend ostream& operator << (ostream& os,Point& that)
 63     {
 64         return os << "x=" << that.x << "," << "y=" << that.y;
 65     }
 66     
 67     friend Point operator - (Point& dest,Point& that);
 68     friend Point operator -= (Point& dest,Point& that);
 69     friend Point operator / (Point& dest,Point& that);
 70     friend Point operator -- (Point& that);
 71     friend Point operator -- (Point& that,int);
 72     friend istream& operator >> (istream& os,Point& that);
 73 };
 74 
 75 Point operator - (Point& dest,Point& that)
 76 {
 77     Point t;//此行代码会调用无参构造
 78     t.x = dest.x - that.x;
 79     t.y = dest.y - that.y;
 80     return t;
 81 }
 82 
 83 Point operator -= (Point& dest,Point& that)
 84 {
 85     dest.x = dest.x - that.x;
 86     dest.y = dest.y - that.y;
 87     return dest;
 88 }
 89 
 90 Point operator / (Point& dest,Point& that)
 91 {
 92     Point t;
 93     t.x = dest.x / that.x;
 94     t.y = dest.y / that.y;
 95     return t;
 96 }
 97     
 98 Point operator -- (Point& that,int)
 99 {
100     Point t(that);//此行代码会调用无参构造
101     that.x--;
102     that.y--;
103     return t;
104 }
105 
106 Point operator -- (Point& that)
107 {
108     that.x--;
109     that.y--;
110     return that;
111 }
112 
113 istream& operator >> (istream& is,Point& that)
114 {
115     return is >> that.x >> that.y;
116 }

 

C++ 双目运算符重载

标签:color   this   pre   hat   +=   amp   c++   调用   operator   

原文地址:https://www.cnblogs.com/xkk956227639/p/9532885.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!