main.cpp:
#include "Complex.h"
int main()
{
Complex z1(6,8);
z1.show();
Complex z2(8,9);
z2.show();
Complex z3;
z3=z1+z2;
z3.show();
Complex z4;
z4=z2-z1;
z4.show();
return 0;
}
#ifndef __cTest__Complex__
#define __cTest__Complex__
#include <iostream>
class Complex
{
private:
double realPart;
double imagePart;
public:
Complex(double rp=0,double ip=0);
~Complex();
double GetRealPart() const;
double GetImagePart() const;
void SetRealPart(double rp);
void SetImagePart(double ip);
void show() const;
Complex operator- (const Complex& a);
};
Complex operator+(const Complex& a,const Complex& b);
#endif
#include "Complex.h"
#include <iostream>
using namespace std;
Complex::Complex(double rp,double ip):realPart(rp),imagePart(ip){};
Complex::~Complex(){};
double Complex::GetRealPart() const
{
return realPart;
}
double Complex::GetImagePart() const
{
return imagePart;
}
void Complex::SetRealPart(double rp)
{
realPart=rp;
}
void Complex::SetImagePart(double ip)
{
imagePart=ip;
}
void Complex::show() const
{
cout << realPart;
if(imagePart<0 && imagePart!=-1)
cout << imagePart <<"i"<<endl;
else if(imagePart==-1)
cout << "-i"<<endl;
else if(imagePart>0 && imagePart!=1)
cout <<"+"<< imagePart <<"i"<<endl;
else
cout << "+i"<<endl;
}
Complex Complex::operator-(const Complex& a)
{
Complex c;
c.realPart=realPart-a.realPart;
c.imagePart=imagePart-a.imagePart;
return c;
}
//global...
Complex operator+(const Complex& a,const Complex& b)
{
Complex c;
c.SetRealPart(a.GetRealPart()+b.GetRealPart());
c.SetImagePart(a.GetImagePart()+b.GetImagePart());
return c;
}