Why must I define a commutative operator twice?

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

提交回复
热议问题