Why must I define a commutative operator twice?

前端 未结 4 1970
[愿得一人]
[愿得一人] 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.

    0 讨论(0)
  • 2021-01-04 12:01

    Order is sometimes important in operators, the classic examples being subraction (-) and division (/). However, it can also apply to multiplication:

    Consider, for example, that they are vectors - x is a (2×1) vector, and y is a (1×2) vector. If we interpret * as matrix multiplication, then x * y is a (2×2) vector, but y * x is a (1×1) vector.

    As such, the C# compiler does not assume that binary operators are commutative, even if they commonly are (addition (+), multiplication (*), etc).

    0 讨论(0)
  • 2021-01-04 12:03

    You don't have to do that - you only need to do that if you want to be able to write:

    MyClass x = ...;
    
    MyClass y = x * 5;
    MyClass z = 5 * x;
    

    If you only want one of the bottom two lines to be valid, you can delete the other operator overload.

    Basically, the C# language doesn't assume that multiplication is commutative even in terms of the types involved.

    0 讨论(0)
  • 2021-01-04 12:09
    class MyClass {
        private int i;
        public MyClass(int x)  {
            i=x;
        }
        public static MyClass  operator+(MyClass a , MyClass  b)  {
            return new MyClass(a.i+b.i);
        }
        public static implicit operator MyClass(int  a) {
            return new MyClass(a);
        }
    
        static void Main(string[] args) {
            MyClass a , b ,c ;
            a=new MyClass(2);
            b=a+4;
            c=4+a;
            Console.WriteLine("B = {0}, C = {1}",b,c);
    
        }
    

    There you go, all you have to do is have the compiler turn int into MyClass instance and then use the MyClass + MyClass method.

    0 讨论(0)
提交回复
热议问题