Problem Description
通过本题目的练习可以掌握成员运算符重载及友元运算符重载
要求定义一个复数类,重载加法和减法运算符以适应对复数运算的要求,重载插入运算符(<<)以方便输出一个复数的要求。
Input
要求在主函数中创建对象时初始化对象的值。
Output
输出数据共有4行,分别代表a,b的值和它们求和、求差后的值
Example Input
无
Example Output
a=3.2+4.5i b=8.9+5.6i a+b=12.1+10.1i a-b=-5.7-1.1i
Hint
Author
黄晶晶
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double a = 0.0, double b = 0.0):real(a),imag(b){};
Complex operator+(Complex &c);
Complex operator-(Complex &c);
friend ostream & operator<<(ostream &out, Complex &c);
void display();
private:
double real;
double imag;
};
Complex Complex :: operator+(Complex &c)
{
return Complex(real + c.real, imag + c.imag);
}
Complex Complex :: operator-(Complex &c)
{
return Complex(real - c.real, imag - c.imag);
}
void Complex :: display()
{
cout<<real;
if(imag > 0)
{
cout<<"+"<<imag<<"i"<<endl;
}
else
{
cout<<imag<<"i"<<endl;
}
}
ostream & operator<<(ostream &out, Complex &c)
{
cout<<c.real;
if(c.imag > 0)
{
cout<<"+"<<c.imag<<"i";
}
else
{
cout<<c.imag<<"i";
}
return out;
}
int main()
{
Complex c1(3.2, 4.5);
cout<<"a="<<c1<<endl;
Complex c2(8.9, 5.6);
cout<<"b="<<c2<<endl;
Complex c3, c4;
c3 = c1+c2;
c4 = c1-c2;
cout<<"a+b="<<c3<<endl;
cout<<"a-b="<<c4<<endl;
return 0;
}