操作符重载的概念

请看程序:
 1 #include <stdio.h>
 2 class Complex
 3 {
 4     int a;
 5     int b;
 6 public:
 7     Complex(int a,int b)
 8     {
 9         this->a = a;
10         this->b = b
11     }
12     friend Complex Add(const Complex&p1,const Complex&p2);
13 };
14 Complex Add(const Complex&p1,const Complex&p2)
15 {
16     Complex ret;
17     ret.a = p1.a + p2.a;
18     ret.b = p1.b + p2.b;
19     
20     return ret;
21 }
22 int main()
23 {
24     Complex c1(1,2);
25     Complex c2(3,4);
26     Complex c3 = Add(c1,c2);
27     printf("c3.a = %d,c3.b = %d
",c3.a,c3.b);
28     return 0;
29 }
思考一个问题,在以上程序中,Add函数可以解决Complex对象相加的问题,但是Complex是现实世界中确实存在的复数,并且复数在数学中的地位和普通的实数相同,那为什么不能让 + 操作符也支持复数相加呢??
知识点:
  • C++中的重载能够扩展操作符的功能
  • 操作符的重载以函数的方式进行
  • 本质:用特殊形式的函数扩展操作符的功能
  • 通过operator关键字可以定义特殊的函数
  • operator的本质是通过函数重载操作符

操作符重载语法:

1 Type operator Sign(const Type p1,const Type p2)
2 {
3     Type ret;
4     return ret;
5 }

Sign为系统中预定义的操作符,如+ ,-, *, /,等

 1 #include <stdio.h>
 2 class Complex
 3 {
 4     int a;
 5     int b;
 6 public:
 7     Complex(int a = 0,int b = 0)
 8     {
 9         this->a = a;
10         this->b = b;
11     }
12     int getA()
13     {
14         return a;
15     }
16     int getB()
17     {
18         return b;
19     }
20     friend Complex operator + (const Complex& p1,const Complex& p2);
21 };
22 Complex operator + (const Complex& p1,const Complex& p2)
23 {
24     Complex ret;
25     ret.a = p1.a + p2.a;
26     ret.b = p1.b + p2.b;
27     return ret;
28 }
29 int main()
30 {
31     Complex c1(1,2);
32     Complex c2(3,4);
33     Complex c3 = c1 + c2;
34     printf("c3.a = %d,c3.b = %d
",c3.getA(),c3.getB());
35     return 0;
36 }
37  
  • 可以将操作符重载函数定义为类的成员函数
  1. 比全局操作符重载函数少一个参数(左操作数)
  2. 不需要依赖友元就可以完成操作符重载
  3. 编译器优先在成员函数中寻找操作符重载函数
   
 1 class Type
 2 {
 3 public:
 4     Type operator Sign(const Type&p)
 5     {
 6         Type ret;
 7         return ret;
 8     }
 9};
10 #include <stdio.h>
11 class Complex
12 {
13     int a;
14     int b;
15 public:
16     Complex(int a = 0,int b = 0)
17     {
18         this->a = a;
19         this->b = b;
20     }
21     int getA()
22     {
23         return a;
24     }
25     int getB()
26     {
27         return b;
28     }
29     Complex operator + (const Complex& p)
30     {
31         Complex ret;
32         ret.a = this->a + p.a;
33         ret.b = this->b + p.b;
34         return ret;
35     }
36 };
37 int main()
38 {
39     Complex c1(1,2);
40     Complex c2(3,4);
41     Complex c3 = c1 + c2;//c1.operator + (c2)
42     printf("c3.a = %d,c3.b = %d
",c3.getA(),c3.getB());
43     return 0;
44 }
小结:
  1. 操作符重载是C++的强大特性之一
  2. 操作符重载的本质是通过函数扩展操作符的功能
  3. opeartor关键字是实现操作符重载的关键
  4. 操作符重载遵循相同的函数重载规则
  5. 全局函数和成员函数都可以实现对操作符的重载
主要记录的是学习听课的笔记
原文地址:https://www.cnblogs.com/chengeputongren/p/12176201.html