Is it possible to overload the operator or create something for exponentiation like 3^2 or (3)2 well or 3**2 ?
- oneFor erection in the steppe you can use the static method of the class Math - Pow Math.Pow (3, 2) - Yankov Viacheslav
- This is not kosher. I want to overload the operator inta. As a method, only an operator. - Nazar Kalytiuk
- study msdn.microsoft.com/ru-ru/library/8edha89s.aspx. But to create your own operator, alas, will not succeed. Anyway, I failed. - rdorn
|
2 answers
You cannot override an existing statement for those types for which it is defined. And you cannot think of a new symbol denoting an operator, you must overload an existing operator.
Also, you cannot overload the operator if none of the operands is your type . For example, you cannot define the ^ operator for a string and a number. However, here it is possible:
class X { int v; public X(int v) { this.v = v; } public static implicit operator X (int i) { return new X(i); } static public double operator ^ (X x, int y) { return Math.Pow(xv, y); } } At the same time (X)5 ^ 2 will give 25.
- I do not advise you to use the override operator ^ for exponentiation. This is not obvious and generally wrong. For educational purposes, you can play, but no more. - Yankov Viacheslav
- @syler: Why me? So the question is formulated. - VladD
|
Can so
SomeClass a = new SomeClass() { Var = 2 }; SomeClass b = new SomeClass() { Var = 2 }; SomeClass c = new SomeClass(); c = a ^ b; class SomeClass { public int Var { get; set; } public static SomeClass operator ^(SomeClass a, SomeClass b) { SomeClass tmpClass = new SomeClass(); tmpClass.Var = (int)Math.Pow(a.Var, b.Var); return tmpClass; } } |