定义一个复数类Complex,重载运算符“+”,

定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算符能够都是类对象。也能够其中一个是整数,顺序任意。例如:c1+c2,i+c1,c1+i 均合法(设i为整数,c1 c2为复数)。编程序 分别求两个复数之和,整数和复数之和。ios

 

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