C++ 操作符重载

1、为什么要使用操作符重载?

操作符和方法在本质上一样,使用操作符更符合人性化的描述。

2、操作符重载分为 普通操作符重载和成员操作符重载,区别在于:

  a、普通操作符重载要访问对象的私有成员,因此要设计为friend,而成员操作符重载不需要;

  b、相比于普通操作符重载,成员操作符重载,少了一个形参,因为成员方法总是与对象绑定使用的,被绑定的对象就是操作符的第一个参数;


 示例代码:

 1 #include "StdAfx.h"
 2 
 3 class Point
 4 {
 5 private :
 6     int x;
 7     int y;
 8 
 9 public :
10     Point ();
11 
12     Point(int x,int y);
13 
14     void Print()const;
15 
16     void Set(int x,int y);
17 
18     friend Point operator+(const Point& a, const Point& b);
19 
20     friend Point operator+(const Point& a, int b);
21 
22     Point operator-(const Point& b)
23     {
24         Point s;
25         s.Set(this->x-b.x, this->y-b.y);
26         return s;
27     }
28 
29     Point operator-(int b)
30     {
31         Point s;
32         s.Set(this->x-b, this->y-b);
33         return s;
34     }
35 };
View Code
 1 #include "StdAfx.h"
 2 #include <iostream>
 3 #include "Point.h"
 4 
 5 Point ::Point()
 6 {
 7 }
 8 
 9 Point::Point(int x,int y)
10 {
11     this->x = x;
12     this->y = y;
13 }
14 
15 void Point::Print()const
16 {
17     std::cout<<"X:"<<x<<" Y:"<<y<<std::endl;
18 }
19 
20 Point operator+(const Point& a,const Point& b)
21 {
22     Point s(a.x+b.x,a.y+b.y);
23 
24     return s;
25 }
26 
27 
28 Point operator+(const Point& a,int b)
29 {
30     Point s(a.x+b,a.y+b);
31 
32     return s;
33 }
34 
35 void Point::Set(int x,int y)
36 {
37     this->x = x;
38     this->y = y;
39 }
View Code
原文地址:https://www.cnblogs.com/nzbbody/p/3364086.html