学习写类,各位指点下

2 views
Skip to first unread message

wang bin

unread,
Dec 30, 2009, 9:12:38 PM12/30/09
to DS计划——C深入学习项目
#include<iostream>
using namespace std;
class complex
{
private:
float a;
float b;
public:
complex(float a=0,float b=0);
complex(const complex &x);
~complex();
complex & operator =(const complex &x);
friend bool operator ==(const complex &s,const complex &x);
friend bool operator !=(const complex &s,const complex &x);
complex operator +(const complex &x);
complex operator -(const complex &x);
complex operator *(const complex &x);
complex operator /(const complex &x);
friend void operator +=( complex &s,const complex &x);
friend void operator -=( complex &s,const complex &x);
friend void operator *=( complex &s,const complex &x);
friend void operator /=( complex &s,const complex &x);
void tostring();
};

complex::complex(float a,float b)
{
this->a=a;
this->b=b;
}
complex::~complex()
{
a=b=0;
}
complex::complex(const complex &x)
{
this->a=x.a;
this->b=x.b;
}
bool operator == (const complex &s,const complex &x)
{
if((s.a==x.a) &&(s.b==x.b))
return true;
return false;
}
bool operator !=(const complex &s,const complex &x)
{
if((s.a==x.a) &&(s.b==x.b))
return false;
return true;
}
complex &complex::operator =(const complex &x)
{
this->a=x.a;
this->b=x.b;
return *this;
}
complex complex::operator +(const complex &x)
{
complex tmp;
tmp.a=this->a+x.a;
tmp.b=this->b+x.b;
return tmp;
}
complex complex::operator -(const complex &x)
{
complex tmp;
tmp.a = this->a-x.a;
tmp.b = this->b-x.b;
return tmp;
}

complex complex::operator *(const complex &x)
{
complex tmp;
tmp.a = this->a*x.a-this->b*x.b;
tmp.b = this->a*x.b+this->b*x.a;
return tmp;
}
complex complex::operator /(const complex &x)
{
complex tmp;
if(!this->b&&!x.b)
{
tmp.a = this->a/x.a;
tmp.b = 0;
return tmp;
}
float i = this->b*this->b+x.b*x.b;
tmp.a = (this->a*x.a+this->b*x.b)/i;
tmp.b = (this->b*x.a-this->a*x.b)/i;
return tmp;
}

void complex::tostring()
{
cout<<this->a<<"+"<<this->b<<"i"<<endl;
}

void operator+=(complex &s,const complex &x)
{
s.a=s.a+x.a;
s.b=s.b+x.b;
}

void operator -=(complex &s,const complex &x)
{
s.a=s.a-x.a;
s.b=s.b-x.b;
}

void operator*=(complex &s,const complex &x)
{
s.a=s.a*x.a-s.b*x.b;
s.b=s.a*x.b+x.a*s.b;
}

void operator/=(complex &s,const complex &x)
{
if(!s.b&&!x.b)
{
s.a = s.a/x.a;
s.b = 0;
}
else
{
float i = s.b*s.b+x.b*x.b;
s.a = (s.a*x.a+s.b*x.b)/i;
s.b = (s.b*x.a-s.a*x.b)/i;
}
}

Reply all
Reply to author
Forward
0 new messages