ym1123568700 2024-06-04 23:14 采纳率: 50%
浏览 4
已结题

我这个代码应该怎么改才能正常使用成员函数来重载复合运算符 “+”


#include<iostream>
using namespace std;
class complex
{
   private:
     double real;
     double imag;
   public:
       complex(double r=0,double i=0)
       {
            real=r;imag=i;    
    }
    complex operator+(complex &);
    void show()
    {
        cout<<real<<","<<imag<<endl;
    }
};
complex complex::operator+(complex &c)
{
    complex t;
    t.real=this->real+c.real;
    t.imag=this->imag+c.imag;
    return t;
}
int main()
{
    complex c1(3,4.3),c2(6,3.5),c;
    c=c1+c2;
    c1.show();
    return 0;
}
  • 写回答

2条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-06-04 23:14
    关注

    引自免费微信小程序:皆我百晓生

    在给定的代码中,main() 函数中的 c = c1 + c2; 行会导致编译错误,因为在这种情况下,你需要为临时对象调用一个可接受两个引用作为参数的重载加法运算符。为了修复这个问题,只需在 main() 中创建一个临时变量来接收相加的结果,并将其赋值给 c

    下面是修改后的代码:

    #include<iostream>
    using namespace std;
    
    class complex
    {
    private:
        double real;
        double imag;
    public:
        complex(double r = 0, double i = 0)
        {
            real = r;
            imag = i;
        }
        complex operator+(const complex &c) const // 添加const关键字
        {
            complex t;
            t.real = this->real + c.real;
            t.imag = this->imag + c.imag;
            return t;
        }
        void show()
        {
            cout << real << "," << imag << endl;
        }
    };
    
    int main()
    {
        complex c1(3, 4.3), c2(6, 3.5);
        complex c; // 将 c 定义为 complex 类型
        c = c1 + c2; // 使用临时变量接收结果并赋值给 c
        c.show();
        return 0;
    }
    

    在这个修改版的代码中,我做了以下几个改动:

    1. complex::operator+ 的定义中添加了 const 关键字,这表示它不会修改任何成员变量。这是个好的编程习惯,因为它允许您对常量对象使用此运算符。
    2. 修改了 main() 函数,将 c 定义为 complex 类型,并通过临时变量接收 c1 + c2 的结果,然后将其赋值给 c。这样可以正确地使用成员函数重载的复合运算符 +
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月15日
  • 已采纳回答 6月7日
  • 创建了问题 6月4日

悬赏问题

  • ¥15 如何用数码管显示学号(相关搜索:单片机)
  • ¥15 错误于library(org.Hs.eg.db): 不存在叫‘org.Hs.eg.db’这个名称的程序包,如何解决?
  • ¥60 求一个图片处理程序,要求将图像大小跟现实生活中的大小按比例联系起来的
  • ¥50 求一位精通京东相关开发的专家
  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活
  • ¥15 sqlserver中加密的密码字段查询问题