friend-Funktionen
-
Hallo,
ich habe ein Problem mit friend-Funktionen.
Hier erstmal der Code, aus meinem Buch:#include <iostream> using namespace std; class Euro { private: long data; // Euros * 100 + Cents public: Euro( int euro = 0, int cents = 0) { if( euro < 0) // Euro(-1,20) == Euro(-1.20) cents = -cents; data = 100L * (long)euro + cents; } Euro( double x) { x *= 100.0; // Runden, z.B. data = (long)( x >= 0.0 ? x+0.5 : x-0.5); // 9.7 -> 10 } // ---- Operatorfunktionen ---- friend Euro operator+( const Euro& e1, const Euro& e2); friend Euro operator-( const Euro& e1, const Euro& e2); friend Euro operator*( const Euro& e, double x) { Euro temp( ((double)e.data/100.0) * x) ; return temp; } friend Euro operator*( double x, const Euro& e) { return e * x; } }; // Addition: inline Euro operator+( const Euro& e1, const Euro& e2) { Euro temp; temp.data = e1.data + e2.data; return temp; } // Subtraktion: inline Euro operator-( const Euro& e1, const Euro& e2) { Euro temp; temp.data = e1.data - e2.data; return temp; }
friend Euro operator+( const Euro& e1, const Euro& e2);
Sehe ich das richtig, dass fuer diese Definition das Schluesselwort 'friend'
notwendig ist, weil diese Funktion ausserhalb der Klasse deklariert ist, ohne den Bereichsoperator '::'
und somit keine Methode der Klasse ist?friend Euro operator*( const Euro& e, double x) { Euro temp( ((double)e.data/100.0) * x) ; return temp; }
Weshalb brauche ich hier 'friend'?
Die Funktion ist doch innerhalb der Klasse deklariert, also ist sie doch eine vollwertige Methode. IMHO ist friend ueberfluessig, um auf die private-Elemente zuzugreifen, da die Funktion eine Methode ist.mfg
und Danke schonmal
Raptor
-
Raptor schrieb:
Weshalb brauche ich hier 'friend'?
Die Funktion ist doch innerhalb der Klasse deklariert, also ist sie doch eine vollwertige Methode. IMHO ist friend ueberfluessig, um auf die private-Elemente zuzugreifen, da die Funktion eine Methode ist.Obwohl operator* in der Klasse definiert wurde, so ist es trotzdem eine non-Member Funktion. Denn das Schlüsselwort friend bedeutet das
friend heisst: die Funktion ist ein Freund der Klasse. Du kannst jetzt eine Forward Declaration hin schreiben: friend void foo(); oder auch direkt die Funktion implementieren: friend void foo() { something(); } - das ändert nix.
-
Gut, danke schonmal, aber wenn ich jetzt versuche das ganze zu kompilieren,
dann meldet der Compiler einen 'internen Compiler Fehler'.
Es liegt an dieser 2. Defintionfriend Euro operator-( const Euro& e1, const Euro& e2);
Lasse ich sie weg, also wenn nur die +operator Ueberladung dort steht, dann kommt dieser error.