栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

6-1 运算符重载(c++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

6-1 运算符重载(c++)

标题](这里写自本题考虑对运算符进行重载。分别重载复数运算的+,-,*,/,=(赋值)运算符,以及比较大小的<=(复数1的模是否小于等于复数2的模)运算符,其中,比较运算符按复数的模进行比较。测试程序根据输入的mode值分别测试各个函数是否编写正确。定义目录标题)
在这里插入代码片
```在这里描述函数接口:
i#include 
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);

在这里给出函数被调用进行测试的例子:
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]<<" "<
    this->real = real;
    this->imag = imag;
}
Complex Complex::operator+(const Complex & c) const
{
    return Complex(real + c.real, imag + c.imag);
}
Complex Complex::operator-(const Complex& c) const
{
    return Complex(real - c.real, imag - c.imag);
}
Complex Complex::operator*(const Complex& c) const
{
    return Complex(real*c.real-imag*c.imag,real*c.imag+imag*c.real);
}
Complex Complex::operator/(const Complex& c)const
{
    return Complex((real*c.real+imag*c.imag)/(c.real*c.real+c.imag*c.imag),(imag*c.real-real*c.imag)/(c.real*c.real+c.imag*c.imag));
}
Complex Complex::operator=(const Complex& c)
{
    return Complex(this->real = c.real, this->imag = c.imag);
}
bool Complex::operator<=(const Complex& c) const
{
    if (real*real+imag*imag<=c.real*c.real+c.imag*c.imag)
    {
        return 1;
    }
    else
    {
        return 0;
    }
} 

ostream& operator<<(ostream& out, const Complex& c)
{
    out << c.real;
    if (c.imag >=0)
    {
        out << "+";
    }
    out << c.imag<<"i";
    return out;
}
void bubble_sort(Complex fushu[], int n)
{
    Complex cnt;
    for (int i = 0; i < n - 1; ++i) //比较n-1轮
    {
        for (int j = 0; j < n - 1 - i; ++j) //每轮比较n-1-i次,
        {
            if (fushu[j+1]<=fushu[j])
            {
                cnt = fushu[j];
                fushu[j] = fushu[j + 1];
                fushu[j + 1] = cnt;
            }
        }
    }
}

![在这里插入图片描述](https://img-blog.csdnimg.cn/7f1d46ac23fa41df852a610ec07a1185.png)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/889721.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号