1. /*copyright(c)2016.烟台大学计算机学院
  2. * All rights reserved,
  3. * 文件名称:text.Cpp
  4. * 作者:舒文超
  5. * 完成日期:2016年5月12日
  6. * 版本号:vc++6.0
  7. *
  8. * 问题描述:请用类的成员函数,定义复数类重载运算符
  9. +、-、*、/,使之能用于复数的加减乘除。
  10. */
  11. #include<iostream>
  12. using namespace std;
  13. class Complex
  14. {
  15. public:
  16. Complex(){real=0;imag=0;}
  17. Complex(double r,double i){real=r; imag=i;}
  18. Complex operator+(const Complex &c2);
  19. Complex operator-(const Complex &c2);
  20. Complex operator*(const Complex &c2);
  21. Complex operator/(const Complex &c2);
  22. void display();
  23. private:
  24. double real;
  25. double imag;
  26. };
  27. //下面定义成员函数
  28. Complex Complex::operator+(const Complex &c2)
  29. {
  30. Complex c;
  31. c.real=real+c2.real;
  32. c.imag=imag+c2.imag;
  33. return c;
  34. }
  35. Complex Complex::operator-(const Complex &c2)
  36. {
  37. Complex c3;
  38. c3.real=real+c2.real;
  39. c3.imag=imag+c2.imag;
  40. return c3;
  41. }
  42. Complex Complex::operator*(const Complex &c2)
  43. {
  44. Complex c3;
  45. c3.real=real*c2.real;
  46. c3.imag=imag*c2.imag;
  47. return c3;
  48. }
  49. Complex Complex::operator/(const Complex &c2)
  50. {
  51. Complex c3;
  52. c3.real=real/c2.real;
  53. c3.imag=imag/c2.imag;
  54. return c3;
  55. }
  56. void Complex::display()
  57. {
  58. if(imag>0)
  59. cout<<real<<"+"<<imag<<"i"<<endl;
  60. else
  61. cout<<real<<imag<<"i"<<endl;
  62. }
  63. //下面定义用于测试的main()函数
  64. int main()
  65. {
  66. Complex c1(3,4),c2(5,-10),c3;
  67. cout<<"c1=";
  68. c1.display();
  69. cout<<"c2=";
  70. c2.display();
  71. c3=c1+c2;
  72. cout<<"c1+c2=";
  73. c3.display();
  74. c3=c1-c2;
  75. cout<<"c1-c2=";
  76. c3.display();
  77. c3=c1*c2;
  78. cout<<"c1*c2=";
  79. c3.display();
  80. c3=c1/c2;
  81. cout<<"c1/c2=";
  82. c3.display();
  83. return 0;
  84. }