Funktionsweise Operatorüberladung?
-
Hallo,
ich habe mich mal versucht ein bischen in Operatorüberladung reinzuarbeiten..
Ein kleines Test Programm:#include <stdlib.h> #include <iostream> class Zahl { private: int Zahl; public: void setZahl(int zahl) { Zahl = zahl; } int getZahl() { return Zahl; } const Zahl& operator+(const Zahl &z, const Zahl &z2) { return z.getZahl()+z2.getZahl(); } }; int main(int argc, char** argv) { Zahl a, b, c; a.setZahl(2); b.setZahl(3); c = a+b; // -> a.getZahl()+b.getZahl() cout << c.getZahl(); return (EXIT_SUCCESS); }Naja so in etwa sollte es doch funktionieren oder?
3 Fehlermeldungen:
main.cpp:18: error: ISO C++ forbids declaration ofZahl' with no type main.cpp:18: error: expected;' before "operator"
main.cpp:23: error: expected `;' before '}' tokenUnd noch ne andere Frage: Was ist eine Elementfunktion und globale Funktion, und welche Unterschiede haben diese, die bei der Operatorüberladung eine Rolle spielen?
Danke
-
1. Du deklarierst einen Member mit dem selbem Namen wie der Klasse
2. Dein Operator returnet eine referenz auf eine lokale temporäre Variable
3. Dein Operator ist nicht als const deklariert, obwohl du die Klasse nicht änderst
4. Dein Operator ist kein Teil der Klasse sondern ein freier Operator. Der Operator als Teil der Klasse sieht so aus:const Zahl(const Zahl& obj) const { return m_zahl + obj.m_zahl; }
-
5. Deine getZahl Funktion ist auch nicht als const deklariert
-
#include <stdlib.h> #include <iostream> class Zahl { private: int Zahl; public: void setZahl(int zahl) { Zahl = zahl; } int getZahl() const{ return Zahl; } }; Zahl operator+(const Zahl &z, const Zahl &z2) { Zahl r; r.setZahl(z.getZahl()+z2.getZahl()); return r; } int main(int argc, char** argv) { Zahl a, b, c; a.setZahl(2); b.setZahl(3); c = a+b; // -> a.getZahl()+b.getZahl() std::cout << c.getZahl() << '\n'; return EXIT_SUCCESS; }Hab ich Fehler weggemacht.
-
Lies sonst auch mal den Artikel hier:
http://www.c-plusplus.net/forum/viewtopic-var-t-is-232010.htmlSollte deine Fragen so ziemlich alle beantworten können.
