0
#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; }

Can you show me the diffence of complex operator*=(complex b) and complex & operator+=(complex b)

Thanks you very much !

Arne Mertz
  • 24,171
  • 3
  • 51
  • 90
Road Human
  • 123
  • 6
  • complex & operator+=(complex b) returns a reference to *this (the instance of the class the method is called from), while complex operator*=(complex b) returns a copy. –  Nov 09 '15 at 15:33
  • do you want to know the difference between multiplication and addition operators or is it something more subtle like the difference bewteen return by reference/by value? – Arne Mertz Nov 09 '15 at 15:33
  • @ArneMertz The code is the same, so the result is the same. –  Nov 09 '15 at 15:35
  • Where do you have this code from? Don't be confused, the implementation of `*=` is wrong - in this version, both operators have (almost) the same effect. – MikeMB Nov 09 '15 at 15:37
  • @ArneMertz yes, the difference bewteen return by reference/by value? – Road Human Nov 09 '15 at 15:39
  • @ZirconiumHacker complex & operator+=(complex b) returns a reference to *this (the instance of the class the method is called from), while complex operator*=(complex b) returns a copy yes , but i don't understand :( – Road Human Nov 09 '15 at 15:41
  • @ZirconiumHacker thanks, i have just found it at the link http://stackoverflow.com/questions/15847889/difference-between-returning-reference-vs-returning-value-c – Road Human Nov 09 '15 at 15:53

1 Answers1

1

The implementation of operator*= is not correct. It does the same thing as operator+=. In addition, it returns a copy instead of a reference.

A better implementation would be:

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;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270