第八周实验报告(1-2)
来源:互联网 发布:蚁族的奋斗 知乎 编辑:程序博客网 时间:2024/05/17 02:10
01.#include <iostream> 02. 03.using namespace std; 04.class Complex 05.{ 06.public: 07. Complex(){real=0;imag=0;} 08. Complex(double r,double i){real=r;imag=i;} 09. friend Complex operator+(Complex &c1,Complex &c2); 10. friend Complex operator-(Complex &c1,Complex &c2); 11. friend Complex operator*(Complex &c1,Complex &c2); 12. friend Complex operator/(Complex &c1,Complex &c2); 13. void display(); 14.private: 15. double real; 16. double imag; 17.}; 18.//下面定义成员函数 19.Complex operator+(Complex &c1,Complex &c2) 20.{ 21. return Complex (c1.real + c2.real,c1.imag + c2.imag); 22.} 23.Complex operator-(Complex &c1,Complex &c2) 24.{ 25. return Complex (c1.real - c2.real,c1.imag - c2.imag); 26.} 27.Complex operator*(Complex &c1,Complex &c2) 28.{ 29. Complex c; 30. 31. c.real = c1.real * c2.real - c1.imag * c2.imag; 32. c.imag = c1.real * c2.imag + c1.imag * c2.real; 33. 34. return c; 35.} 36.Complex operator/(Complex &c1,Complex &c2) 37.{ 38. Complex c; 39. 40. c.real = (c1.real * c2.real + c1.imag * c2.imag)/(c2.imag * c2.imag + c2.real * c2.real); 41. c.imag = (c1.imag * c2.real - c1.real * c2.imag)/(c2.imag * c2.imag + c2.real * c2.real); 42. 43. return c; 44.} 45. 46.void Complex::display() 47.{ 48. cout << "(" << real << "," << imag << "i)" << endl; 49.} 50.int main() 51.{ 52. Complex c1(3,4),c2(5,-10),c3; 53. cout<<"c1 = "; 54. c1.display(); 55. cout<<"c2 = "; 56. c2.display(); 57. c3=c1+c2; 58. cout<<"c1+c2 = "; 59. c3.display(); 60. c3=c1-c2; 61. cout<<"c1-c2 = "; 62. c3.display(); 63. c3=c1*c2; 64. cout<<"c1*c2 = "; 65. c3.display(); 66. c3=c1/c2; 67. cout<<"c1/c2 = "; 68. c3.display(); 69. system("pause"); 70. return 0; 71.}