Überladen von Operatoren

d_Artagne

Mitglied
Hi,


Ich hab mal versucht einen Operator zu überladen. Ich krieg immer
dieselbe Fehlermeldung, aber ich kann mir beim besten Willen nicht
erklären warum. Hier der Code:
Code:
public static bool operator > (DateTime d1, DateTime d2)
		{
			if (d1.Year > d2.Year) { return true; }
			else if (d1.Month > d2.Month) { return true; }
			else if (d1.Day > d2.Day) { return true; }
			return false;
		}

Die Fehlermeldung:

One of the parameters of a binary operator must be the containing type
 
Hi!

Könntest du mal deine ganze Klasse anführen? Hätte eine Vermutung, bin mir aber nicht sicher.

Gruß
TOM
 
Hab da einen Text für dich, der dir helfen sollte. Betrifft zwar den + Operator, aber im Endeffekt eh das gleiche. Ach ja, was mir nur aufgefallen ist. Wenn du > überladest, musst du auch < überladen.

In the operator plus, we are creating a new object whose variable i is the summation of the i's of the objects a and b. The normal plus operator works as usual. We normally overrule the predefined string operator that always gets called whenever our user defined type has to be converted to a string. This is needed to get a confirmation that the plus operator actually did the job it was supposed to do.

Code:
public class zzz {
 
  public static void Main()
  {
  }

}

class yyy {

  public static yyy operator + ( xxx a, xxx b)
  {
    return new yyy();
  }

  public static yyy operator ++ ( xxx a)
  {
    return new yyy();
  }
}

class xxx
{
}
Compiler Error
a.cs(7,19): error CS0563: One of the parameters of a binary operator must be the containing type
a.cs(11,19): error CS0559: The parameter and return type for ++ or -- operator must be the containing type


Whenever an operator is overloaded, one of the parameters to the function must be the data type of the class that contains the operator. In this case, while overloading the binary operator +, at the most one of its parameters must be of type yyy. If not, then it is assumed to be redefining an operator of another class. In the above case, the code of the operator + belongs to class xxx and not yyy.

In the case of a unary operator, it is evident that the only parameter must be the type of the class. In case you have forgotten, the only ternary operator cannot be overloaded. By failing the above rules, you can never supersede an existing predefined operator definition.

The cast operators are resolved using the same principles but by using type names instead of operator symbols. Element access like an array is achieved using indexers that has absolutely has no relationship at all with operator overloads.
 
Zuletzt bearbeitet:

Neue Beiträge

Zurück