Why must I define a commutative operator twice?

前端 未结 4 2003
[愿得一人]
[愿得一人] 2021-01-04 11:26

I wonder if I must define a commutative operator (like *) twice!

public static MyClass operator *(int i, MyClass m)
{
    return new MyClass(i *         


        
4条回答
  •  心在旅途
    2021-01-04 11:55

    For commutative operations, you don't need to implement the entire thing twice, you can reference the initial operator. For example:

        public static Point operator *(Point p, float scalar)
        {
            return new Point(
                    scalar * p.mTuple[0],
                    scalar * p.mTuple[1],
                    scalar * p.mTuple[2]
                );
        }
    
        public static Point operator *(float scalar, Point p)
        {
            return p * scalar;
        }
    

    I hope that this helps.

提交回复
热议问题