I would like to override operator * for my class. I know how to handle * for MyClass * MyClass but how can i implement this for hav开发者_StackOverflow中文版ing possibility to multiply for example:
7 * MyClass
7 is lets say double and MyClass is object of MyClass,
thanks for help
When you provide an operator for your class, the parameter types for the operator implementation control which situations you're handling.
To illustrate:
// Declare which operator to overload (+), the types
// that can be added (two Complex objects), and the
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
This method defines what to do if you want to add two Complex
numbers.
If you tried to use this with (say) a double
and a Complex
, compilation would fail.
In your case, you need just declare both versions:
public static MyClass operator *(MyClass c1, MyClass c2)
{
return ...
}
public static MyClass operator *(double n, MyClass c)
{
return ...
}
The appropriate signature in this case is:
public static MyClass operator *(double a, MyClass b)
This means it takes a double
as the left side, a MyClass
as the right, and returns a MyClass
.
精彩评论