定义一个复数类,用友元函数实现对双目运算符+和*的运算符重载,使其适用于复数运算
#include <cmath>#include <iostream.h>class CComplex{#define err 0.00000001double _x,_y;public:CComplex(double x=0,double y=0):_x(x),_y(y){}CComplex operator+(const CCompl..
·
#include <cmath>
#include <iostream.h>
class CComplex
{
#define err 0.00000001
double _x,_y;
public:
CComplex(double x=0,double y=0):_x(x),_y(y){}
CComplex operator+(const CComplex&z);
CComplex operator*(const CComplex&z);
friend ostream&operator <<(ostream&os,const CComplex&z);
friend istream&operator >>(istream&is,CComplex&z);
};
int main()
{
CComplex z1(0,1.2);
CComplex z2(1,1.2);
cout<<z1+z2<<endl;
cout<<z1*z2<<endl;
cin>>z1;
cout<<z1<<endl;
return 0;
}
CComplex CComplex::operator+(const CComplex&z)
{
CComplex c;
c._x=_x+z._x;
c._y=_y+z._y;
return c;
}
CComplex CComplex::operator*(const CComplex&z)
{
CComplex c;
c._x=_x*z._x-_y*z._y;
c._y=_x*z._y+_y*z._x;
return c;
}
ostream&operator <<(ostream&os,const CComplex&z)
{
if(fabs(z._x)>err)
cout<<z._x;
if(fabs(z._y-1)<err)
cout<<(fabs(z._x)>err?"+i":"i");
else if(fabs(z._y+1)<err)
cout<<"-i";
else if(z._y >err)
cout<<(fabs(z._x)>err?"+":"")<<z._y<<" i";
else if(z._y<-err)
cout<<z._y<<" i";
return os;
}
istream&operator >>(istream&is,CComplex&z)
{
is>>z._x>>z._y;
return is;
}

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)