复数类:
程序如下:
1 #ifndef _COMPLEX_H_ 2 #define _COMPLEX_H_ 3 4 class Complex 5 { 6 double a; 7 double b; 8 public: 9 Complex(double a = 0, double b = 0); 10 double getA(); 11 double getB(); 12 double getModulus(); 13 14 Complex operator + (const Complex& c); 15 Complex operator - (const Complex& c); 16 Complex operator * (const Complex& c); 17 Complex operator / (const Complex& c); 18 19 bool operator == (const Complex& c); 20 bool operator != (const Complex& c); 21 22 Complex& operator = (const Complex& c); 23 }; 24 25 #endif
1 #include "Complex.h" 2 #include "math.h" 3 4 Complex::Complex(double a, double b) 5 { 6 this->a = a; 7 this->b = b; 8 } 9 10 double Complex::getA() 11 { 12 return a; 13 } 14 15 double Complex::getB() 16 { 17 return b; 18 } 19 20 double Complex::getModulus() 21 { 22 return sqrt(a * a + b * b); 23 } 24 25 Complex Complex::operator + (const Complex& c) 26 { 27 double na = a + c.a; 28 double nb = b + c.b; 29 Complex ret(na, nb); 30 31 return ret; 32 } 33 34 Complex Complex::operator - (const Complex& c) 35 { 36 double na = a - c.a; 37 double nb = b - c.b; 38 Complex ret(na, nb); 39 40 return ret; 41 } 42 43 Complex Complex::operator * (const Complex& c) 44 { 45 double na = a * c.a - b * c.b; 46 double nb = a * c.b + b * c.a; 47 Complex ret(na, nb); 48 49 return ret; 50 } 51 52 Complex Complex::operator / (const Complex& c) 53 { 54 double cm = c.a * c.a + c.b * c.b; 55 double na = (a * c.a + b * c.b) / cm; 56 double nb = (b * c.a - a * c.b) / cm; 57 Complex ret(na, nb); 58 59 return ret; 60 } 61 62 bool Complex::operator == (const Complex& c) 63 { 64 return (a == c.a) && (b == c.b); 65 } 66 67 bool Complex::operator != (const Complex& c) 68 { 69 return !(*this == c); 70 } 71 72 Complex& Complex::operator = (const Complex& c) 73 { 74 if( this != &c ) 75 { 76 a = c.a; 77 b = c.b; 78 } 79 80 return *this; 81 }
1 #include <stdio.h> 2 #include "Complex.h" 3 4 int main() 5 { 6 Complex c1(1, 2); 7 Complex c2(3, 6); 8 Complex c3 = c2 - c1; 9 Complex c4 = c1 * c3; 10 Complex c5 = c2 / c1; 11 12 printf("c3.a = %f, c3.b = %f ", c3.getA(), c3.getB()); 13 printf("c4.a = %f, c4.b = %f ", c4.getA(), c4.getB()); 14 printf("c5.a = %f, c5.b = %f ", c5.getA(), c5.getB()); 15 16 Complex c6(2, 4); 17 18 printf("c3 == c6 : %d ", c3 == c6); 19 printf("c3 != c4 : %d ", c3 != c4); 20 21 (c3 = c2) = c1; 22 23 printf("c1.a = %f, c1.b = %f ", c1.getA(), c1.getB()); 24 printf("c2.a = %f, c2.b = %f ", c2.getA(), c2.getB()); 25 printf("c3.a = %f, c3.b = %f ", c3.getA(), c3.getB()); 26 27 return 0; 28 }
为了能实现连续的赋值操作,第72行我们返回的是复数的引用。
主函数的第21行先把c2赋值给c3,然后返回c3,最后将c1赋值给c3,返回c3。
运行结果如下:
注意事项:
小结: