今天总结了对复数类,包括各种运算的重载,希望大家多多指教
#include"stdio.h"
#include"iostream.h"
#include"math.h"
// class
class complex
{
private:
double a,b;
double _copy;
public:
double getreal();
double getimag();
double getZ();
complex(int x)
{
a=x;b=0;
}
complex(double av,double bv):a(av),b(bv)
{
}
complex()
{
}
complex(complex& _copy)
{
a=_copy.a;
b=_copy.b;
}
~complex()//disconstructor
{
}
friend ostream& operator<<(ostream& i,complex& j);
friend istream& operator>>(istream& g,complex& i);
friend complex operator+(complex& x,complex& y);
friend complex operator-(complex& x,complex& y);
friend complex operator*(complex& x,complex& y);
friend complex operator/(complex& x,complex& y);
complex operator+=(complex& y);
complex operator-=(complex& y);
complex operator=(complex& y);
void output()
{
cout<<"z="<<sqrt((a*a)+(b*b))<<endl;
}
void put()
{
cout<<"("<<a<<","<<b<<")"<<endl;
}
};
//output
ostream& operator<<(ostream& stream ,complex& x)
{
x.put();
return stream;
}
//input
istream& operator>>(istream& stream,complex& x)
{
cout<<"\treal=";
cin>>x.a;
cout<<"\timag=";
cin>>x.b;
return stream;
}
//add
complex operator+(complex& x,complex& y)
{
return complex(x.a+y.a,x.b+y.b);
}
//sub
complex operator-(complex& x,complex& y)
{
return complex(x.a-y.a,x.b-y.b);
}
//mul
complex operator*(complex& x,complex &y)
{
return complex((x.a*y.a)-(x.b*y.b),(x.a*y.b)+(x.b*y.a));
}
//div
complex operator/(complex& x,complex& y)
{
return complex(((x.a*y.a+x.b*y.b))/(y.a*y.a+y.b*y.b),(x.b*y.a-x.a*y.b)/(y.a*y.a+y.b*y.b));
}
//+=
complex complex::operator+=(complex& y)
{
this->a+=y.a;
this->b+=y.b;
return *this;
}
//-=
complex complex::operator-=(complex& y)
{
this->a-=y.a;
this->b-=y.b;
return *this;
}
//assignment
complex complex::operator=(complex& y)
{
this->a=y.a;
this->b=y.b;
return *this;
}
double complex::getreal()
{
return a;
}
double complex::getimag()
{
return b;
}
double complex::getZ()
{
return sqrt(a*a+b*b);
}
void main()
{
//class complex
cout<<"\n*****************************************\n";
cout<<"\n**********complex operator***************\n";
cout<<"\n*****************************************\n"<<endl;
complex p,q;
cin>>p;
cout<<p<<endl;
p.output();
cin>>q;
cout<<q<<endl;
q.output();
cout<<"copy constructor"<<endl;
complex _copy;
_copy=p;
_copy.put();
complex div,mul,sub,add;
cout<<"add a+b"<<endl;
add=q+p;
add.put();
cout<<"sub a-b"<<endl;
sub=q-p;
sub.put();
cout<<"mul a*b"<<endl;
mul=p*q;
mul.put();
cout<<"div a/b"<<endl;
div=q/p;
div.put();
cout<<"p+=q"<<endl;
p+=q;
p.put();
complex m,n;
cin>>m;
cout<<m<<endl;
cin>>n;
cout<<n<<endl;
cout<<"m-=n"<<endl;
m-=n;
m.put();
cout<<"p=q"<<endl;
p=q;
p.put();
cout<<"get real"<<endl;
complex _complex;
cin>>_complex;
_complex.getreal();
cout<<"get imag"<<endl;
cin>>_complex;
_complex.getimag();
}