#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;
}
我这个代码应该怎么改才能正常使用成员函数来重载复合运算符 “+”
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
关注 引自免费微信小程序:皆我百晓生
在给定的代码中,
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; }
在这个修改版的代码中,我做了以下几个改动:
- 在
complex::operator+
的定义中添加了const
关键字,这表示它不会修改任何成员变量。这是个好的编程习惯,因为它允许您对常量对象使用此运算符。 - 修改了
main()
函数,将c
定义为complex
类型,并通过临时变量接收c1 + c2
的结果,然后将其赋值给c
。这样可以正确地使用成员函数重载的复合运算符+
。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录- 在
悬赏问题
- ¥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中加密的密码字段查询问题