2运算符重载有什么区别?

时间:2015-11-09 15:31:11

标签: c++

#include<iostream>
using namespace std;
#include<math.h>
class complex {
    float real, image;
public:
    complex(float r = 0, float i = 0)
    {
        real = r; image = i;
    }

    complex & operator+=(complex b)
    {
        real += b.real;
        image += b.image;
        return *this;
    }
    complex  operator*=(complex b)
    {
        real += b.real;
        image += b.image;
        return *this;
    }
    void display()
    {
        cout << real << (image >= 0 ? '+' : '-') << "j*" << fabs(image) << endl;
    }
};
int main() {    return 0; }

你能告诉我复杂算子的差异* =(复数b) 和复杂的operator + =(complex b)

非常感谢你!

1 个答案:

答案 0 :(得分:1)

operator*=的实施不正确。它与operator+=的作用相同。此外,它还会返回副本而不是引用。

更好的实施方式是:

complex& operator*=(complex b)
{
   double tempReal = real*b.real - image*b.image;
   double tempImage = real*b.image + image*b.real; 
   real = tempReal;
   image = tempImage;
   return *this;
}