1 //运算符重载:友元函数方式
2 #include <iostream.h>
3
4 class complex //复数类
5 {
6 public:
7 complex(){ real = imag = 0;}
8 complex(double r, double i)
9 {
10 real = r;
11 imag = i;
12 }
13 friend complex operator + (const complex &c1, const complex &c2); //相比于成员函数方式,友元函数前面加friend,形参多一个,去掉类域
14 friend complex operator - (const complex &c1, const complex &c2); //成员函数方式有隐含参数,友元函数方式无隐含参数
15 friend complex operator * (const complex &c1, const complex &c2);
16 friend complex operator / (const complex &c1, const complex &c2);
17
18 friend void print(const complex &c); //友元函数
19
20 private:
21 double real; //实部
22 double imag; //虚部
23
24 };
25
26 complex operator + (const complex &c1, const complex &c2)
27 {
28 return complex(c1.real + c2.real, c1.imag + c2.imag);
29 }
30
31 complex operator - (const complex &c1, const complex &c2)
32 {
33 return complex(c1.real - c2.real, c1.imag - c2.imag);
34 }
35
36 complex operator * (const complex &c1, const complex &c2)
37 {
38 return complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.real + c1.imag * c2.imag);
39 }
40
41 complex operator / (const complex &c1, const complex &c2)
42 {
43 return complex( (c1.real * c2.real + c1.imag * c2. imag) / (c2.real * c2.real + c2.imag * c2.imag),
44 (c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag) );
45 }
46
47 void print(const complex &c)
48 {
49 if(c.imag < 0)
50 cout<<c.real<<c.imag<<‘i‘<<endl;
51 else
52 cout<<c.real<<‘+‘<<c.imag<<‘i‘<<endl;
53 }
54
55 int main()
56 {
57 complex c1(2.0, 3.5), c2(6.7, 9.8), c3;
58 c3 = c1 + c2;
59 cout<<"c1 + c2 = ";
60 print(c3); //友元函数不是成员函数,只能采用普通函数调用方式,不能通过类的对象调用
61
62 c3 = c1 - c2;
63 cout<<"c1 - c2 = ";
64 print(c3);
65
66 c3 = c1 * c2;
67 cout<<"c1 * c2 = ";
68 print(c3);
69
70 c3 = c1 / c2;
71 cout<<"c1 / c2 = ";
72 print(c3);
73 return 0;
74 }