4-1 复数类的运算符重载

                                                                        4-1 复数类的运算符重载

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

通过本题目的练习可以掌握成员运算符重载及友元运算符重载

要求定义一个复数类,重载加法和减法运算符以适应对复数运算的要求,重载插入运算符(<<)以方便输出一个复数的要求。

Input

 

要求在主函数中创建对象时初始化对象的值。

Output

 

输出数据共有4行,分别代表ab的值和它们求和、求差后的值

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

#include <iostream>
using namespace std;
class Complex
{
double real;
double imag;
public:
Complex(double r=0,double i=0):real(r),imag(i){};
void Display();
Complex operator +(Complex &);
Complex operator -(Complex &);
friend ostream& operator <<(ostream &,Complex &);
};
ostream & operator <<(ostream & OUT,Complex &C)
{
OUT<<C.real;
if(C.imag<0)
OUT<<C.imag<<"i"<<endl;
else if(C.imag>0)
OUT<<"+"<<C.imag<<"i"<<endl;
else
OUT<<"0i"<<endl;
return OUT;
}
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);
}
int main()
{
Complex a(3.2,4.5),b(8.9,5.6),c,d;
cout<<"a=";
cout<<a;
cout<<"b=";
cout<<b;
c=a+b;
cout<<"a+b=";
cout<<c;
d=a-b;
cout<<"a-b=";
cout<<d;
return 0;
}

posted @ 2016-10-24 20:33  Philtell  阅读(171)  评论(0编辑  收藏  举报