PRzeciążanie operatorów - operator * i kolejność działania

0

Mam kod dla liczb zespolonych (ucze sie obiektowości). Wiem, że mnożenie jest nipoprawne, ale nie o to teraz chodzi - pytanie jest inne. Mam kod, i on działa:

#include <iostream>
#include <ostream>
using namespace std;

class complex {
	protected:
	double Re, Im;

	public:
	complex() : Re(0.0), Im(0.0) {} // konstruktor bezargumentowy
	complex(double Re, double Im) : Re(Re), Im(Im) {} // konstruktor z dwoma argumentami
	double getRe() const { return Re; }
	double getIm() const { return Im; }
	friend complex operator+(const complex&, const complex&); // funkcja zaprzyjaźniona
	friend ostream& operator<<(ostream&, const complex&); // funkcja zaprzyjaźniona

	complex operator*(const double d)
    {
        return complex( this->Re * d, this->Im * d);
    }

    complex& operator=(const complex& s)
    {
        this->Re = s.Re;
        this->Im = s.Im;
        return *this;
    }

};

ostream& operator<<(ostream& out, const complex &a) {
	out << "(" << a.getRe() << ", " << a.getIm() << ")" << endl;
	return out;
}


int main()
{
    complex c(3,4);
    cout << c;

    c = c * 2;
    cout << c;

}

Jednak jak napiszę:

c = 2*c;

dostaję błąd:

error: no match for ‘operator*’ (operand types are ‘int’ and ‘complex’)|

Co jest nie tak i czy można to poprawić, aby pisać również c = 2*c; ? (oraz dla innych działań: -,+,/)? Dziękuję!

0
#include <iostream>
#include <ostream>
using namespace std;
 
class complex
  {
   public:
   double Re,Im;  // po kiego to chowasz? Czy jest jakiÅ zestaw wartoÅci (Re,Im) dla których liczba zespolona jest bezsensowna?
   complex(double Re=0,double Im=0):Re(Re),Im(Im) {}
  };
complex operator+(const complex &a,const complex &b) { return complex(a.Re+b.Re,a.Im+b.Im); }
complex operator*(const complex &a,const complex &b) { return complex(a.Re*b.Re-a.Im*b.Im,a.Re*b.Im+a.Im*b.Re); }
ostream &operator<<(ostream &out,const complex &a) { return out<<'('<<a.Re<<','<<a.Im<<')'; }
 
 
int main()
  {
   complex c(3,4);
   cout<<c<<' '<<2+c<<' '<<c+2<<' '<<c+c<<endl;
   cout<<c<<' '<<2*c<<' '<<c*2<<' '<<c*c<<endl;
   return 0;
  }

1 użytkowników online, w tym zalogowanych: 0, gości: 1