+= operator überladen



  • Hi 🙂

    Ich hätte noch eine Frage zum Überladen vom += Operator.

    Da habe ich folgendes Programm dazu:

    automat.h:

    #ifndef _AUTOMAT_H_
    #define _AUTOMAT_H_
    #include "automat.h"
    
    class Automat {
      private:
        unsigned long geld = 0;
    
      public:
        unsigned long operator+=(unsigned long);
        unsigned long get_geld() const;
    };
    
    #endif
    

    automat.cpp:

    #include "automat.h"
    
    unsigned long Automat::operator+=(unsigned long g) {
      return (geld += g);
    }
    unsigned long Automat::get_geld() const {
      return geld;
    }
    

    main.cpp:

    #include <iostream>
    #include "automat.h"
    using namespace std;
    
    int main(void) {
    
      Automat data01;
      data01+=100;
      cout << data01.get_geld() << endl;
    
      return 0;
    }
    

    Bei diesem Programm kam mir etwas seltsam vor. Dass die += Methode nämlich etwas zurückliefert. Wenn man sich das Hauptprogramm anschaut, sieht man, dass da nichts zurückgegeben wird.

    Darum habe ich automat.h und automat.cpp etwas umgeschrieben (und main.cpp unverändert belassen).

    automat.h:

    #ifndef _AUTOMAT_H_
    #define _AUTOMAT_H_
    #include "automat.h"
    
    class Automat {
      private:
        unsigned long geld = 0;
    
      public:
        void operator+=(unsigned long); // jetzt void
        unsigned long get_geld() const;
    };
    
    #endif
    

    automat.cpp:

    #include "automat.h"
    
    void Automat::operator+=(unsigned long g) {
      geld += g;
    }
    unsigned long Automat::get_geld() const {
      return geld;
    }
    

    Und siehe da, es funktioniert genau so.

    Ist das wirklich nötigt, dass die += Methode einen return hat?



  • Rueckgabewerte koennen ignoriert werden & die Methode muss nichts zurueckgeben. Die Antwort lautet also: Nein.



  • Die normalen += Operatoren (für int, double usw.) geben etwas zurück, also macht man das bei eigenen Typen auch so.



  • Hm, widersprechen sich diese beiden Aussagen? 😕



  • Nein.



  • Es muss nichts zurückgegeben werden, aus Konistenz zu built-ins sollte man aber *this zurückgeben.



  • Aha, ok. Danke 🙂


Anmelden zum Antworten