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

定义一个复数类Complex,重载运算符"+".使之能用于复数的加法运算,将运算符函数重载为非成员、非友员的普通函数。编写程序求2个复数之和。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.     double real;  
  10.     double imag;  
  11. };  
  12.  
  13. void Complex::display()  
  14. {  
  15.     cout<<"("<<real<<","<<imag<<"i)";  
  16. }  
  17.  
  18. Complex operator +(Complex &c1,Complex &c2)  
  19. {  
  20.     Complex p;  
  21.     p.real=c1.real+c2.real;  
  22.     p.imag=c1.imag+c2.imag;  
  23.     return p;  
  24. }  
  25. int main()  
  26. {  
  27.     Complex c1(5,2),c2(1,3),c3;  
  28.     c1.display();  
  29.     cout<<"+";  
  30.     c2.display();  
  31.     cout<<"=";  
  32.     c3=c1+c2;  
  33.     c3.display();  
  34.