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

书籍源码

开发平台:

Visual C++

  1. #include <iostream>        //用VC++时改为∶ #include <iostream.h>
  2. using namespace std;      //用VC++时为取消此行
  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+(int &i);
  9.    friend Complex operator+(int&,Complex &);
  10.    void display();
  11.   private:
  12.    double real;
  13.    double imag;
  14.  };
  15.  
  16. Complex Complex::operator+(Complex &c)
  17. {return Complex(real+c.real,imag+c.imag);}
  18.  
  19. Complex Complex::operator+(int &i)
  20. {return Complex(real+i,imag);}
  21. void Complex::display()
  22. {cout<<"("<<real<<","<<imag<<"i)"<<endl;}
  23. Complex operator+(int &i,Complex &c)
  24. {return Complex(i+c.real,c.imag);}
  25. int main()
  26. {Complex c1(3,4),c2(5,-10),c3;
  27.  int i=5;
  28.  c3=c1+c2;
  29.  cout<<"c1+c2=";
  30.  c3.display();
  31.  c3=i+c1;
  32.  cout<<"i+c1=";
  33.  c3.display();
  34.  c3=c1+i;
  35.  cout<<"c1+i=";
  36.  c3.display();
  37.  return 0;
  38. }