四则运算

bzsc / 2023-05-25 / 原文

#include <iostream>
using namespace std;

/*请在这里填写答案*/
class Complex
{
public:
    Complex(double a=0, double b=0)
      {
        real=a;
        imag=b;
      }
    
    Complex operator+(Complex &a)
      {
        Complex temp;
        temp.real=this->real+a.real;
        temp.imag=this->imag+a.imag;
        return temp;
      }
    
    Complex operator-(Complex &a)
      {
        Complex temp;
        temp.real=this->real-a.real;
        temp.imag=this->imag-a.imag;
        return temp;
      }
    
    Complex operator*(Complex &c2)
      {
        return Complex(real*c2.real-imag*c2.imag,imag*c2.real+real*c2.imag);
      }
    
    Complex operator/(Complex &c2)
      {
       return Complex((real*c2.real+imag*c2.imag)/(c2.imag*c2.imag+c2.real*c2.real),(imag*c2.real-real*c2.imag)/(c2.imag*c2.imag+c2.real*c2.real));
      }
    
    double real;
    double imag;
};
ostream &operator<<(ostream &out,Complex &p)
{
    if(p.imag>0)
        
        out << p.real << "+" << p.imag << "i";
    
    else
        
        out << p.real<< p.imag << "i";
    return out;
}
istream &operator>>(istream &out,Complex &p)
{
    out>>p.real>>p.imag;
    return out;
}



int main()      //主函数
{
    Complex c1(1, 1), c2(-1, -1), c3;    //定义复数类的对象
    cin>>c1;
    cout <<c1<<endl;
    cout <<c2<<endl;
    c3 = c1 - c2;
    cout << c3<<endl;
    c3 = c1 + c2;
    cout << c3<<endl;
    c3=c1 * c2;
    cout << c3<<endl;
    c3=c1 / c2;
    cout << c3<<endl;
    return 0;
}