Operator-overload/Operatorfunkiton



  • Hallo Forum,
    in C++/Cli habe ich nach entsprechendem Support aus diesem Form Operatorfunktionen wie folgt definiert z.B. für eine komplexe Zahl:

    // Operations
    		complex^operator+(const complex^ v) {
    			return gcnew complex(_real + v->_real,  _imag + v->_imag);
    		}
    		complex^operator-(const complex^ v) {
    			return gcnew complex(_real - v->_real,  _imag - v->_imag);
    		}
    		complex^operator*(const complex^ v) {
                                         //x1 *  x2         -   y1 *    y2           x1 * y2        +   x2 * y1
    			return gcnew complex( ( (_real*v->_real)   - (_imag*v->_imag)  ), (_real*v->_imag  +  v->_real* _imag) );
    
    		}
    		complex^operator=(const complex^v) {
    			return gcnew complex(_real = v->_real, _imag = v->_imag);
    		}
    

    So jetzt versuche ich das Ganze mal (mit Abstrichen) in C#:

    // Operations
            public static Complex operator +(Complex first, Complex second)
            {
                return new Complex(first._real + second._real, first._imag + second._imag); 
            }    
    		public static Complex operator-(Complex first, Complex second) {
    			return new Complex(first._real - second._real, first._imag - second._imag);
    		}
    
            public static Complex operator *(Complex first, Complex second)
            {
                return new Complex(((first._real * second._real) - (first._imag * second._imag)), (first._real * second._imag + second._real * first._imag));
    
            }
    
    // so wie hier geht’s jedenfalls nicht:
    
    		public static Complex operator=(Complex first, Complex second) {
    			return new Complex(first._real = second._real, first._imag = second._imag);
    		}
    

    Könnt Ihr mir sagen, was ich anstelle des „=“ Operator machen kann, um doch so eine Art Zuweisungsoperator zu erhalten ?



  • Der operator= in C++/CLI sieht sehr komisch aus. Der weißt der aktuellen Instanz die Werte zu und erzeugt dann ein neues Objekt, das zurückgegeben wird?! Den operator= gibts in C# in dem Sinne nicht. Falls dein Complex eine Struct ist, passiert schon automatisch das, was du willst. Falls es eine Klasse ist, musste du sowas wie eine "void CopyIntoMe(Complex other)" Funktion anbieten. Aber so eine Funktion hab ich noch nie vermisst.


Anmelden zum Antworten