# c++：复数的运算符重载

``````#include <iostream>
using namespace std;

class Complex {
double real;
double imag;
public:
//构造函数
Complex(double real=0, double imag=0);

//operator+-*/=操作符函数
Complex operator+(const Complex& c) const;
Complex operator-(const Complex& c) const;
Complex operator*(const Complex& c) const;
Complex operator/(const Complex& c) const;
Complex operator=(const Complex& c);

//operator <=操作符函数
bool operator<=(const Complex& c) const;

//友元函数声明以帮助operator<<()函数访问Complex类的私有成员
friend ostream& operator<<(ostream& out, const Complex& c);
};

//n个复数，按模从小到达排序
void bubble_sort(Complex[],int n);

``````

bubble_sort函数按冒泡排序的算法对n个复数按模从小到大的顺序排序。

``````int main() {
double dReal1, dImag1, dReal2, dImag2;

int mode;
cin>>mode;
cin>>dReal1>>dImag1>>dReal2>>dImag2;
Complex c1(dReal1, dImag1);
Complex c2(dReal2, dImag2);
Complex c[6] = {c1,c2,c1+c2,c1-c2,c1*c2,c1/c2};
switch(mode)
{
case 1: cout << c[0]<<" "<<c[1];break;
case 2: cout << c[2];break;
case 3: cout << c[3];break;
case 4: cout << c[4];break;
case 5: cout << c[5];break;
case 6: bubble_sort(c,6);
for(int i=0;i<6;i++)
cout<<c[i]<<" ";

}

return 0;
}
/* 请在这里填写答案 */

``````

``````
#include<math.h>
Complex::Complex(double r,double i)
{
real=r;
imag=i;
}
Complex Complex::operator+(const Complex &c) const
{
Complex c1;
c1.real=real+c.real;
c1.imag=imag+c.imag;
return c1;
}
Complex Complex::operator-(const Complex &c) const
{
Complex c1;
c1.real=real-c.real;
c1.imag=imag-c.imag;
return c1;
}
Complex Complex::operator=(const Complex &c)
{
Complex c1;
c1.real=real*c.real;
c1.imag=imag*c.imag;
return c1;
}
Complex Complex::operator/(const Complex &c) const
{
Complex c1;
c1.real=(real*c.real+imag*c.imag)/(c.imag*c.imag+c.real*c.real);
c1.imag=(imag*c.real-real*c.imag)/(c.imag*c.imag+c.real*c.real);
return c1;
}
Complex Complex::operator*(const Complex &c) const
{
Complex c1;
c1.real=real*c.real-imag*c.imag;
c1.imag=real*c.imag+imag*c.real;
return c1;
}
ostream& operator<<(ostream& out, const Complex& c)
{
if(c.imag>0)
out<<c.real<<"+"<<c.imag<<"i";
else
out<<c.real<<"+"<<c.imag;
return out;
}

double distance(double r,double i)
{
return sqrt(pow(r,2)+pow(i,2));
}
bool Complex::operator<=(const Complex &c) const
{
double a,b;
a=distance(real,imag);
b=distance(c.real,c.imag);
if(a<=b) return true;
else return false;
}
//n个复数，按模从小到达排序
void bubble_sort(Complex D[],int n)
{
int i,j;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(!(D[j]<=D[j+1]))
{
Complex temp=D[j];
D[j]=D[j+1];
D[j+1]=temp;
}
}
}
}
``````

``````6
1 2 3 4
``````

• 写回答

#### 3条回答默认 最新

• 关注
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

• 系统已结题 5月25日
• 已采纳回答 5月17日
• 创建了问题 5月17日

#### 悬赏问题

• ¥15 为什么eprime输出的数据会有缺失？
• ¥20 腾讯企业邮箱邮件可以恢复么
• ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗？
• ¥15 错误 LNK2001 无法解析的外部符号
• ¥50 安装pyaudiokits失败
• ¥15 计组这些题应该咋做呀
• ¥60 更换迈创SOL6M4AE卡的时候，驱动要重新装才能使用，怎么解决？
• ¥15 让node服务器有自动加载文件的功能
• ¥15 jmeter脚本回放有的是对的有的是错的
• ¥15 r语言蛋白组学相关问题