您的位置:首页 > 编程语言 > C语言/C++

C++实现的复数运算符重载

2012-11-03 20:22 323 查看
//#include<iostream>
//using namespace std;
#include <iostream.h>
class Complex
{
private:
double real;
double img;
public:
Complex(double lp=0.0,double rp=0.0);//构造函数
Complex(const Complex &rth);//拷贝构造函数
Complex &operator =(const Complex& rh);//赋值运算符
void Print()
{
cout<<real<<"+"<<img<<"i"<<endl;
}
friend Complex operator+(const Complex& lp,const Complex& rp);
friend Complex operator-(const Complex& lp,const Complex& rp);
friend Complex operator*(const Complex& lp,const Complex& rp);
};

Complex ::Complex(double t_real,double t_img)
{
real=t_real;
img=t_img;
}
Complex::Complex(const Complex &rth)
{
*this=rth;
}

Complex& Complex::operator=(const Complex& rth)
{
if (this==&rth)
return *this;
else
{
real=rth.real;
img=rth.img;
return  *this;
}

}
Complex operator+(const Complex& cp1,const Complex& cp2)
{

return Complex(cp1.real+cp2.real,cp1.img+cp2.img);

}

Complex operator-(const Complex& cp1,const Complex& cp2)
{
return Complex(cp1.real-cp2.real,cp1.img-cp2.img);
}

Complex operator*(const Complex&cp1,const Complex&cp2)
{
return Complex (cp1.real*cp2.real-cp1.img*cp2.img,cp1.real*cp2.img+cp2.real*cp1.img);
}

int main ()
{
Complex lp(2,3);
Complex rp(1,1);
Complex res;
Complex cb(lp);
res=lp+rp;
cout<<"The + result: ";
res.Print();
res=lp-rp;
cout<<"The - result: ";
res.Print();
res=lp*rp;
cout<<"The * result: ";
res.Print();
res=cb;
cout<<"The = result: ";
res.Print();
return 0;
}


最近写的关于C++ 复数运算符重载的,特分享一下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: