1.要求:在程序的适当位置填写程序代码,使用友元函数方法实现下列运算符重载: - 爱问答

(爱问答)

1.要求:在程序的适当位置填写程序代码,使用友元函数方法实现下列运算符重载:

1) 复数 / 实数(double)  运算

(2) 复数 == 复数  运算; (结果:int型,1表示“true”,0表示“false”)

(3) 复数 != 复数  运算。(结果:int型,1表示“true”,0表示“false”)

 

程序代码:

#include <iostream>

using namespace std;

 

class Complex

{

private:

    double real,image;                 //分别为实部、虚部

public:

    Complex(double rel=0, double img=0)

    {

       real=rel;

       image=img;

    }

 

    void display()                  //输出(a+b*i) 、(a-b*i) 、(a)等形式

    {

       cout<<" ("<<real;

       if (image>0)

           cout<<"+"<<image<<"*i) ";   //虚部为正

       else if (image<0)

           cout<<image<<"*i) ";        //虚部为负

       else

           cout<<") ";                 //虚部为,即为实数

    }

 

    friend Complex operator -(Complex & c1,Complex & c2);//用友元函数重载

 

};

 

//友元函数的定义

Complex operator -(Complex & c1,Complex & c2)

{

    Complex temp;

    temp.real=c1.real-c2.real;

    temp.image=c1.image-c2.image;

    return temp;

}

 

int main()

{

    Complex c1(10,9), c2(3,-4),c3;

    c3=c1/5;

 

    //输出除的结果

    c1.display();

    cout<<"/";

    cout<<5;

    cout<<"=";

    c3.display();

    cout<<endl;

 

    //输出比较的结果

    cout<<"c1==c2 ? 结果:";

    cout<<(c1==c2)<<endl;

 

    cout<<"c1!=c2 ? 结果:";

    cout<<(c1!=c2)<<endl;

    return 0;

}

2.能否不调用display()成员函数,而是采用cout<<…<<…<<…方式连续输出Complex呢?

 

这个算是简单的作业了,你完全可以参考已有的,写要求的,简单的参考

在类中的声明

   friend Complex operator /(Complex & c1,int x);
   friend bool operator ==(Complex & c1,Complex & c2);
   friend bool operator !=(Complex & c1,Complex & c2);

定义为

Complex operator /(Complex & c1,int x)
{
   Complex temp;
   temp.real=c1.real/x;
   temp.image=c1.image/x;
   return temp;
}
bool operator ==(Complex & c1,Complex & c2)
{
 return (c1.real==c2.real) && (c1.image==c2.image);
}
 bool operator !=(Complex & c1,Complex & c2)
{
 return (c1.real!=c2.real) || (c1.image!=c2.image);
}

而采用cout<<…<<…<<…方式,任何教材上都有的,你参考下自己先写下

相关标签:运算

下一篇:以下两种情况你认为哪个情况更适合使用数据透视表?为什么?

上一篇:c++语言怎么让计算机打印1到100再回到1

热门标签:
excel 网盘 破解 word dll
最新更新:
微软重新评估新的Outlook的使用时机 联想推出搭载联发科Helio G80芯片组的Tab M9平板 英特尔创新大赛时间确定! 微软Edge浏览器在稳定渠道中推出Workspaces功能 英伟达RTX4060TiGPU推出MaxSun动漫主题! 谷歌地图为用户提供了街景服务! GameSir 在T4 Kaleid中推出了一款出色的控制器! 微软开始在Windows 11 中测试其画图应用程序的新深色模式! LG电子推出全球首款无线OLED电视 英伟达人工智能芯片崭露头角! Steam Deck可以玩什么游戏-Steam Deck价格限时优惠 雷蛇推出CobraPro鼠标 Kindle电子阅读器可以访问谷歌商店吗 Windows10如何加入组策略 window10图片查看器怎么没有了?