View Code
1 // 文件complex.h: 复数类的定义
2 #ifndef __COMPLEX__H__
3 #define __COMPLEX__H__
4
5 class Complex
6 {
7 public:
8 Complex(double = 0.0, double = 0.0);
9 Complex operator + (const Complex &) const;
10 Complex operator - (const Complex &) const;
11 //Complex & operator = (const Complex &);
12 void print()const;
13
14 private:
15 double real; // 实数部分
16 double imaginary; // 虚数部分
17 };
18
19 #endif
20 // 文件complex.cpp: 复数类的实现
21 #include <iostream.h>
22 #include "complex.h"
23
24 Complex::Complex(double r, double i)
25 {
26 real = r;
27 imaginary = i;
28 }
29
30 void Complex::print()const
31 {
32 cout << '(' << real << ", " << imaginary << ')';
33 }
34
35 Complex Complex::operator + (const Complex &operand2) const
36 {
37 Complex sum;
38 sum.real = real + operand2.real;
39 sum.imaginary = imaginary + operand2.imaginary;
40 return sum;
41 }
42
43 Complex Complex::operator - (const Complex &operand2) const
44 {
45 Complex diff;
46 diff.real = real - operand2.real;
47 diff.imaginary = imaginary - operand2.imaginary;
48 return diff;
49 }
50
51 //Complex &Complex::operator = (const Complex &right)
52 //{
53 // real = right.real;
54 // imaginary = right.imaginary;
55 // return *this;
56 //}
57 // 文件ex13_1.cpp: 主函数定义,通过运算符操作复数对象
58 #include <iostream.h>
59 #include "complex.h"
60
61 int main()
62 {
63 Complex x, y(4.3, 8.2), z(3.3, 1.1);
64
65 // 输出x,y,z
66 cout << "x: ";
67 x.print();
68 cout << "\ny: ";
69 y.print();
70 cout << "\nz: ";
71 z.print();
72
73 //输出加法运算
74 x = y + z;
75 cout << "\n\nx = y + z:\n";
76 x.print();
77 cout << " = ";
78 y.print();
79 cout << " + ";
80 z.print();
81
82 //输出减法运算
83 x = y - z;
84 cout << "\n\nx = y - z:\n";
85 x.print();
86 cout << " = ";
87 y.print();
88 cout << " - ";
89 z.print();
90 cout << '\n';
91
92 return 0;
93 }