xt10-2.cpp
上传用户:liubin
上传日期:2022-06-13
资源大小:85k
文件大小:1k
源码类别:

书籍源码

开发平台:

Visual C++

  1. #include <iostream>
  2. using namespace std;
  3. class Complex
  4.  {public:
  5.    Complex(){real=0;imag=0;}
  6.    Complex(double r,double i){real=r;imag=i;}
  7.    Complex operator+(Complex &c2);
  8.    Complex operator-(Complex &c2);
  9.    Complex operator*(Complex &c2);
  10.    Complex operator/(Complex &c2);
  11.    void display();
  12.   private:
  13.    double real;
  14.    double imag;
  15.  };
  16.  
  17. Complex Complex::operator+(Complex &c2)
  18. {Complex c;
  19.  c.real=real+c2.real;
  20.  c.imag=imag+c2.imag;
  21.  return c;}
  22.  
  23. Complex Complex::operator-(Complex &c2)
  24. {Complex c;
  25.  c.real=real-c2.real;
  26.  c.imag=imag-c2.imag;
  27.  return c;}
  28. Complex Complex::operator*(Complex &c2)
  29. {Complex c;
  30.  c.real=real*c2.real-imag*c2.imag;
  31.  c.imag=imag*c2.real+real*c2.imag;
  32.  return c;}
  33. Complex Complex::operator/(Complex &c2)
  34. {Complex c;
  35.  c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
  36.  c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
  37.  return c;}
  38. void Complex::display()
  39. {cout<<"("<<real<<","<<imag<<"i)"<<endl;}
  40. int main()
  41. {Complex c1(3,4),c2(5,-10),c3;
  42.  c3=c1+c2;
  43.  cout<<"c1+c2=";
  44.  c3.display();
  45.  c3=c1-c2;
  46.  cout<<"c1-c2=";
  47.  c3.display();
  48.  c3=c1*c2;
  49.  cout<<"c1*c2=";
  50.  c3.display();
  51.  c3=c1/c2;
  52.  cout<<"c1/c2=";
  53.  c3.display();
  54.  return 0;
  55. }