Funktionsrückgabewert



  • Hallo!

    Ich ärgere mich gerade mit etwas C++-Code rum, habe da wohl noch etwas grundlegendes nicht verstanden.

    class MyClass
    {
      public:
         float _x, _y;
    
         MyClass(const MyClass& c) : _x(c._x), _y(c._y) {}
         MyClass(float x, float y) : _x(x), _y(y) {}
    
         MyClass getChanged()
         {
            return MyClass(_x*_x, _y*_y);
         }
    };
    
    int main(int argc, char *argv[])
    {
      const MyClass a(1.0f, 1.5f);
      const MyClass b(a.getChanhged());
    }
    

    Das konstante Objekt a macht hier Probleme, ich ging immer davon aus das das return MyClass(...); aus Zeile 11 mir ein neues Objekt zurückliefert und nicht das bestehende überschreibt...

    Würde mich über Hilfe oder einen Hinweis freuen!

    Gruß Vanish



  • du musst dem Compiler nochmal sagen, dass Getchanged das Object nicht verändert.

    class MyClass
    {
      public:
         float _x, _y;
    
         MyClass(const MyClass& c) : _x(c._x), _y(c._y) {}
         MyClass(float x, float y) : _x(x), _y(y) {}
    
         MyClass getChanged() const // <------- hier muss ein const hin
         {
            return MyClass(_x*_x, _y*_y);
         }
    };
    

  • Mod

    VanishOxiAction schrieb:

    Das konstante Objekt a macht hier Probleme, ich ging immer davon aus das das return MyClass(...); aus Zeile 11 mir ein neues Objekt zurückliefert und nicht das bestehende überschreibt...

    Das weist du, aber der Funktionssignatur kann man das nicht entnehmen. Für die syntaktische Zulässigkeit der Funktionsaufrufs kommt es nur auf den Funktionstyp an.



  • Dieser Link erklärt alles nochmal:
    http://tutorial.schornboeck.net/constmethode.htm



  • Danke für die Antworten, sie haben mir schon sehr weitergeholfen!

    Nur leider kommt jetzt noch eine Fehlermeldung:

    error C2166: L-Wert gibt ein const-Objekt an

    Gruß Vanish



  • Also bei mir kompiliert es ohne Probleme:

    class MyClass
    {
      public:
         float _x, _y;
    
         MyClass(const MyClass& c) : _x(c._x), _y(c._y) {}
         MyClass(float x, float y) : _x(x), _y(y) {}
    
         MyClass getChanged() const
         {
            return MyClass(_x*_x, _y*_y);
         }
    }; 
    
    int main( int argc, char** argv )
    {
      const MyClass a(1.0f, 1.5f);
      const MyClass b(a.getChanged());
    
      return( 0 );
    }
    

    Poste mehr Quelltext, ansonsten:
    http://msdn.microsoft.com/en-us/library/5ew12bxy(VS.71).aspx



  • Sorry, super danke es läuft!
    Ich hatte im return-Wert einen Arithmetischen Zuweisungsoperator (*=) drinnen.... Eindeutig Zeit fürs Bett. Danke für die tolle Hilfe!

    Gruß Vanish


Anmelden zum Antworten