Binärer Operator funktioniert nicht
-
Hallo!
Ich hab da so eine Klasse (für komplexe Zahlen) und einen Operator für Multiplikation:class t_complex { public: //... //blah blah //... t_complex &operator*(const t_complex &c) { //... blah } };Funktioniert auch alles wunderbar mit der Multiplikation.
Nun hab ich ja aber auch noch eine Klasse, die sieht so aus:template <class T, int height, int length> class t_matrix { public: T array[height][length]; //... };Und für diese Klasse hab ich auch so einen schönen Operator (Multiplikation der Matrix mit einem Skalar):
template <class T, int length, int height> t_matrix<T, height, length> operator*(const T &c, const t_matrix<T, height, length> &m) { t_matrix<T, height, length> ret; for (int i=0; i<height; i++) for (int j=0; j<length; j++) ret.array[i][j]=c*m.array[i][j]; return ret; }Wenn ich nun aber so eine Matrix (aus komplexen Zahlen) mit einer komplexen Zahl multiplizieren will, meckert der Compiler bei folgender Zeile:
ret.array[i][j]=c*m.array[i][j];Die Einträge des Array sind ja vom Typ t_complex, genau wie c.
Der Compiler erzählt mir folgendes:error C2678: binary '*' : no operator found which takes a left-hand operand of type 'const t_complex' (or there is no acceptable conversion)Das finde ich nicht nett.
Wenn ich allerdings die komplexe Multiplikation außerhalb des Klassenkörpers definiere, wie folgtt_complex operator*(const t_complex &c1, const t_complex &c2) { t_real re; t_real im; re=c1.real*c2.real-c2.imag*c1.imag; im=c1.imag*c2.real+c2.imag*c1.real; return t_complex(re, im); }, dann meckert er nicht.
Kann mir jemand erklären, was das soll?
Danke schon mal im Voraus,
Moritz
-
Dein Member-operator ist nicht als const deklariert, daher kann er nur angewendet werden, wenn der linke Operand (*this) nicht const ist. Mach's doch mal so:
t_complex &operator*(const t_complex &c) const { // ...Dass der Operator eine Referenz zurückgibt, lässt mich übrigens auf einen Fehler schließen. Entweder gibst du eine Referenz auf eine lokale Variable zurück, oder änderst das Objekt selbst.
-
MFK schrieb:
Dein Member-operator ist nicht als const deklariert, daher kann er nur angewendet werden, wenn der linke Operand (*this) nicht const ist. Mach's doch mal so:
t_complex &operator*(const t_complex &c) const { // ...Ach so geht das. Jetzt funktioniert's. Danke.
MFK schrieb:
Dass der Operator eine Referenz zurückgibt, lässt mich übrigens auf einen Fehler schließen. Entweder gibst du eine Referenz auf eine lokale Variable zurück, oder änderst das Objekt selbst.
Ja, das hatte ich nur falsch abgetippt. Steht gar nicht so als Referenz in meinem Code.