【CPP0048】复数类四则运算及插入/提取操作
为复数类Complex重载实现+,-,*,/,<<,>>等运算符,main(void)函数完成对其的测试。@
Complex类结构说明:
Complex类的数据成员包括:
①私有数据成员:实部real(double型),虚部imag(double型)。
Complex类成员函数包括:
①有参构造函数Complex(double, double),其中参数默认值为0。
②重载运算符+以实现两个Complex的加法运算。
③重载运算符-以实现两个Complex的减法运算。
④重载运算符*以实现两个Complex的乘法运算。
⑤重载运算符/以实现两个Complex的除法运算。
⑥重载运算符<<以实现Complex对象的格式输出,输出格式要求:
<实部>+<虚部>i
例如:10.0,10.0+4.7i,10.0-4.7i,-4.7i,0等。
⑦重载运算符>>以实现Complex对象的格式输入,输入格式要求:
<实部>+<虚部>i
例如:10.0,10.0+4.7i,10.0-4.7i,-4.7i,0等。
###裁判测试程序样例:
#include <iostream>
using namespace std;
/*请在这里填写答案*/
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;
}
###输入样例:
10.0-4.7i
###输出样例:
10-4.7i
-1-1i
11-3.7i
9-5.7i
-14.7-5.3i
-2.65+7.35i
#include <iostream>
using namespace std;
/*请在这里填写答案*/
class Complex
{
private:
double real;
double imag;
public:
Complex(double real1=0,double imag1=0):real(real1),imag(imag1){}
Complex operator+(Complex &c2);
Complex operator-(Complex &c2);
Complex operator*(Complex &c2);
Complex operator/(Complex &c2);
friend ostream& operator<<(ostream &out,Complex &c);
friend istream& operator>>(istream &in,Complex &c);
};
Complex Complex::operator+(Complex &c2)
{
return Complex(real+c2.real,imag+c2.imag);
}
Complex Complex::operator-(Complex &c2)
{
return Complex(real-c2.real,imag-c2.imag);
}
Complex Complex::operator*(Complex &c2)
{
return Complex(real*c2.real-imag*c2.imag,imag*c2.real+real*c2.imag);
}
Complex 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));
}
ostream& operator<<(ostream& out, Complex& c) {
if(c.imag>0)
out << c.real << "+" << c.imag << "i";
else
out << c.real<< c.imag << "i";
return out;
}
istream& operator>>(istream& in, Complex& c) {
in >> c.real >> c.imag;
return in;}
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;
}