重载+号运算符!

大道如海 2003-05-21 07:29:06
我在做一个复数的实例时,用到+号运算符的重载.
我试着写了一个,可以运行,但不知道符不符合运算符重载的规则,或者说下面的写法有没有不妥的地方。如果有,如何改正。
Complex Complex::operator+(Complex right)
{
realPart += right.realPart ;
imaginaryPart += right.imaginaryPart ;

return *this;
}
...全文
66 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
meteor135 2003-05-21
  • 打赏
  • 举报
回复
Complex Complex::operator+(Complex const &right)
{
realPart += right.realPart ;
imaginaryPart += right.imaginaryPart ;

return this; //这里对吗?this可是指针哦!改成return *this;
}

forever1314 2003-05-21
  • 打赏
  • 举报
回复
no problem!
大道如海 2003-05-21
  • 打赏
  • 举报
回复
TO:xieha(右边的话是正确的,左边的话是错误的)
似乎return this这句话有问题。
煜知搬砖者 2003-05-21
  • 打赏
  • 举报
回复
sorry,上面写错了:呵呵,

Complex Complex::operator+(Complex const &right)
{
realPart += right.realPart ;
imaginaryPart += right.imaginaryPart ;

return this;
}
煜知搬砖者 2003-05-21
  • 打赏
  • 举报
回复
Complex& Complex::operator+(Complex const &right)
{
realPart += right.realPart ;
imaginaryPart += right.imaginaryPart ;

return this;
}
realdreamer 2003-05-21
  • 打赏
  • 举报
回复
msdn 有例子:

// operator_overloading.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
class Complex
{
public:
Complex( double r, double i ) : re(r), im(i) {}
Complex operator+( Complex &other );
void Display( ) { cout << re << ", " << im << endl; }
private:
double re, im;
};

// Operator overloaded using a member function
Complex Complex::operator+( Complex &other )
{
return Complex( re + other.re, im + other.im );
}

void main()
{
Complex a = Complex( 1.2, 3.4 );
Complex b = Complex( 5.6, 7.8 );
Complex c = Complex( 0.0, 0.0 );

c = a + b;
c.Display();
}
大道如海 2003-05-21
  • 打赏
  • 举报
回复
realPart,imaginaryPart为代表实部和虚部的成员变量。

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧