问题描述

完成两个复数的加减

代码

#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r=0, double i=0):real(r), imag(i){}
Complex operator+(Complex &a) const{
Complex temp;
temp.real=this->real+a.real;
temp.imag=this->imag+a.imag;
return temp;
//return Complex(real+a.real,imag+a.imag);
}//重载双目运算符'+'
Complex operator-=(Complex &a){

this->real-=a.real;
this->imag-=a.imag;
return Complex(real,imag);
} //重载双目运算符'-='
friend Complex operator-( Complex a,Complex b) {

Complex temp;
temp.real=a.real-b.real;
temp.imag=a.imag-b.imag;
return temp;
}
//重载双目运算符'-'
void Display() const;
private:
double real;
double imag;
};

void Complex::Display() const
{
cout << "(" << real << ", " << imag << ")" << endl;
}

int main()
{
double r, m;
cin >> r >> m;
Complex c1(r, m);
cin >> r >> m;
Complex c2(r, m);
Complex c3 = c1+c2;
c3.Display();
c3 = c1-c2;
c3.Display();
c3 -= c1;
c3.Display();
return 0;
}