#include "operatorOverload.h"
#include<complex>
using namespace std;
int main()
{
Complex c1(1,2),c2(4,-5),c3,c4,c5;
c3 = c1+c2;
c4 = c1*c2;
c5 = c1/c2;
c3.print();
c4.print();
c5.print();
complex<double> d1(1,2),d2(4,-5),d3,d4,d5;
d3=d1+d2;
d4=d1*d2;
d5=d1/d2;
cout<<"d3="<<d3.real()<<" "<<d3.imag()<<endl;
cout<<"d4="<<d4.real()<<" "<<d4.imag()<<endl;
cout<<"d5="<<d5.real()<<" "<<d5.imag()<<endl;
return 0;
}
//.h文件
#include<string>
#include<string.h>
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r= 0,double i = 0)
{
real = r;
image = i;
// cout <<"构造函数被调用"<<endl;
}
void print()
{
if(image >0) cout<<real <<"+" <<image<<"i"<<endl;
else if(image <0) cout <<real <<image<<"i"<<endl;
else cout <<real;
}
Complex operator*(const Complex &c);
friend Complex operator + (const Complex &c1,const Complex &c2);
friend Complex operator / (const Complex &c1,const Complex &c2);
private :
double real,image;
};
Complex operator /(const Complex &c1,const Complex &c2)
{
Complex c3;
double a,b,c,d;
a = c1.real;b = c1.image;c = c2.real; d = c2.image;
c3.real = (a*c + b*d)/(c*c+d*d);
c3.image = (b*c - a*d)/(c*c+d*d);
return c3;
}
Complex operator+(const Complex &c1,const Complex &c2)
{
Complex c3;
c3.real = c1.real+c2.real;
c3.image = c1.image +c2.image;
return c3;
}
Complex Complex ::operator *(const Complex &c)
{
Complex c3;
c3.real = real * c.real - image *c.image;
c3.image = real * c.image + image * c.real;
return c3;
}