Overloading the + operator to add two arrays

后端 未结 5 1727
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 18:53

What\'s wrong with this C# code? I tried to overload the + operator to add two arrays, but got an error message as follows:

One of the parameters of a binary operato

5条回答
  •  眼角桃花
    2020-12-03 19:25

    Its states that one of the parameters to the operator needs to be of the same type as the operator function is a member of. So if the operator function is a member of MyClass on of the parameters needs to be of type MyClass.

    class MyClass
    {
     ...
    
    public static int[] operator+(MyClass x, int[] y)
      // public static int[] Add(int[] x, int[] y)
      {
          int[] z = new int[x.Length];
    
          for (int i = 0; i < x.Length; i++)
          {
            z[i] = x[i] + y[i];
          }
    
          return (z);
      }
    }
    

提交回复
热议问题