其实c++中各种运算符,都是很特殊的一类函数,运算符函数
不过还是和普通函数有区别的
函数意味着它们可以被重载,这样方便程序员重载一些运算符
说白了,就是你可以自定义这个运算规则
下面是复数类实现加减乘除的运算
加减 用普通成员函数实现
乘除 用友元类成员函数实现
1 #include<bits/stdc++.h>
2 using namespace std;
3 #define cp Complex
4
5 class Complex
6 {
7 private:
8 double r,i;
9 public:
10 Complex(double R = 0,double I = 0):r(R),i(I){};
11 //成员函数实现
12 Complex operator+(Complex b);
13
14 Complex operator-(Complex b);
15
16 //友元函数实现
17 friend Complex operator*(Complex a,Complex b);
18
19 friend Complex operator/(Complex a,Complex b);
20
21 void display();
22 };
23
24 //类外实现函数
25 Complex Complex::operator+(Complex b)
26 {
27 return Complex(r + b.r,i + b.i);
28 }
29
30 Complex Complex::operator-(Complex b)
31 {
32 return Complex(r - b.r,i - b.i);
33 }
34
35 Complex operator*(Complex a,Complex b)
36 {
37 Complex t;
38 t.r = a.r*b.r - a.i*b.i;
39
40 t.i = a.r*b.i + b.r*a.i;
41 return t;
42 }
43
44 Complex operator/(Complex a,Complex b)
45 {
46 Complex t;
47 double fm = 1 / (b.r*b.r + b.i*b.i);
48
49 t.r = (a.r*b.r + a.i*b.i)*fm;
50 t.i = (a.i*b.r - a.r*b.i)*fm;
51 return t;
52 }
53
54 void Complex::display()
55 {
56 if(i == 0) cout << r << endl;
57 else cout << r << ((i > 0)?" + ":"") << i << "i" << endl;
58 }
59
60 void test()
61 {
62 cp c1(1,2),c2(3,4),c3,c4,c5,c6;
63 c3 = c1 + c2;
64 c4 = c1 - c2;
65 c5 = c1 * c2;
66 c6 = c1 / c2;
67
68 c1.display();
69 c2.display();
70 c3.display();
71 c4.display();
72 c5.display();
73 c6.display();
74 }
75 int main()
76 {
77 test();
78 return 0;
79 }
