//定义复数类complex class complex{ private: int real; //实部 int image; //虚部 public: complex(int x=0,int y=0){ real = x; image = y; } //构造函数 //重载加号运算符,功能为:两个复数对象相加 friend complex operator + (const complex& a, const complex& b) { complex c; c.real = a.real + b.real; c.image = a.image + b.image; return c; } } //使用 complex a(2,5),b(7,8),c; c = a + b;
#include<iostream.h>
#include<math.h>
class Complex
{
public:
Complex()
{
this->real=0;
this->image=0;
}
Complex(double a,double b);
Complex(const Complex &c);
void showComplex() const
{
if(image<0)
{
cout<<"("<<real<<image<<"i"<<")";
}else{
cout<<"("<<real<<"+"<<image<<"i"<<")";
}
}
void setComplex(double a,double b)
{
real=a;
image=b;
}
double getReal() const
{
return real;
}
double getImage() const
{
return image;
}
Complex getConj() const
{
Complext c(real,-image);
return c;
}
double getAbs() const
{
return sqrt(real*real+image*image);
}
double getInstance(const Complex &c)
{
return sqrt((real-c.real)*(real-c.real)+(image-c.image)*(image-c.image));
}
Complex operator +(const Complex &a)
{
return Complex(real+a.real,image+a.image);
}
Complex operator +(const double a) const
{
return Complex(real+a,image);
}
Complex operator -(const Complex &b)
{
return Complex(real-b.real,image-b.image);
}
Complex operator -(const double b)
{
return Complex(real-b,image);
}
Complex operator *(const Complex &c)
{
return Complex(real*c.real,image*c.image);
}
Complex operator *(const double c)
{
return Complex(real*c,image);
}
Complex operator /(const Complex &c)
{
return Complex((real*c.real+image*c.image)/(c.real*c.real+c.image*c.image),(image*c.real-real*c.image)/(c.real*c.real+c.image*c.image));
}
Complex operator /(const double c)
{
return Complex(real/c,image/c);
}
Complex operator =(const Complex &c)
{
return Complex(c.real,c.image);
}
bool operator==(const Complex &c) const;
private:
double real;
double image;
};
Complex::Complex(double a,double b)
{
this->real=a;
this->image=b;
}
Complex::Complex(const Complex &c)
{
real=c.real;image=c.image;
}
bool Complex::operator==(const Complex &c)
{
if(c.real==real && c.image==image)
return true;
else
return false;
}
void main(void)
{
cout<<"OK"<<endl;
Complex z1(23.12,234.1);
Complex z2(21.2,-89.09);
z1.showComplex();
cout<<"/";
z2.showComplex();
Complex z3;
z3=z1/z2;
cout<<"=";
z3.showComplex();
cout<<endl;
}