Define the Complex class.
输入
8.1
6.2
2.7
5.9
输出
c1 + c2 = 10.8 + 12.1 i
c1 - c2 = 5.4 + 0.3 i
主程序 (不能修改)
#include <iostream>
using namespace std;
#include "source.cpp"
int main(){
Complex c1, c2, c3;
cin >> c1 >> c2;
c3 = c1 + c2;
cout << "c1 + c2 = " << c3 << endl;
c3 = c1 - c2;
cout << "c1 - c2 = " << c3 << endl;
}
我的答案
class Complex
{
double real,imag;
public:
Complex(){
real=0;
imag=0;
}
Complex(double a,double b){
this->real=a;
this->imag=b;
}
friend ostream & operator<<( ostream & os,const Complex & c);
friend istream & operator>>( istream & is,Complex & c);
Complex operator + (const Complex& x){
return Complex(this->real+x.real,this->imag+x.imag);
}
Complex operator - (const Complex& x){
return Complex(this->real-x.real,this->imag-x.imag);
}
};
ostream & operator<<( ostream & os,const Complex & c)
{
os << c.real << " + " << c.imag << " i"; //输出复数
return os;
}
istream & operator>>( istream & is,Complex & c)
{
is>>c.real;
is>>c.imag;
return is;
}