Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading the + operator to add two arrays

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 operator must be the containing type.

class Program
{
  public static void Main(string[] args)
  {
      const int n = 5;

      int[] a = new int[n] { 1, 2, 3, 4, 5 };
      int[] b = new int[n] { 5, 4, 3, 2, 1 };
      int[] c = new int[n];

      // c = Add(a, b);
      c = a + b;

      for (int i = 0; i < c.Length; i++)
      {
        Console.Write("{0} ", c[i]);
      }

      Console.WriteLine();
  }

  public static int[] operator+(int[] 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);
  }
}
like image 568
Anton Kreuzer Avatar asked Nov 06 '09 12:11

Anton Kreuzer


People also ask

How can we add two numbers using operator overloading?

To perform addition of two numbers using '-' operator by Operator overloading. Binary operators will require one object as an argument so they can perform the operation. If we are using Friend functions here then it will need two arguments. The operator is being invoked: ob1-ob2.

Can we add two arrays in CPP?

If you're trying to add the values of two array elements and store them in an array, the syntax is as simple as: arr1[i] = arr2[i] + arr3[i]; But this assumes that the arrays have been declared and arr2 and arr3 have been initialized. and fifth you are printing the result before you're done computing it.

What is operator overloading with example?

This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

Can we add two objects using operator?

yes of course you can add two object of same class but before doing that you have to do operator overloading , by defining the '+' operator and how the objects are going to add when u simply put a '+' operator between the object.


2 Answers

Operators must be declared inside a "related" class' body. For instance:

public class Foo
{
    int X;

    // Legal
    public static int operator+(int x, Foo y);

    // This is not
    public static int operator+(int x, int y);
}

Since you don't have access to the implementation of arrays, your best bet would be to either wrap your arrays in your own implementation so you can provide additional operations (and this is the only way to make the operator+ work.

On the other hand, you could define an extension method like:

public static class ArrayHelper
{
    public static int[] Add(this int[] x, int[] y) { ... }
}

The will still lead to natural calls (x.Add(y)) while avoiding to wrap arrays in your own class.

like image 169
Bryan Menard Avatar answered Oct 25 '22 19:10

Bryan Menard


You can use something like this:

class Program {
  static void Main(string[] args) {
    const int n = 5;

    var a = new int[n] { 1, 2, 3, 4, 5 }.WithOperators();
    var b = new int[n] { 5, 4, 3, 2, 1 };

    int[] c = a + b;

    for (int i = 0; i < c.Length; i++) {
      Console.Write("{0} ", c[i]);
    }

    Console.WriteLine();
  }
}

public static class Int32ArrayExtensions {
  public static Int32ArrayWithOperators WithOperators(this int[] self) {
    return self;
  }
}

public class Int32ArrayWithOperators {
  int[] _array;

  public Int32ArrayWithOperators(int[] array) {
    if (array == null) throw new ArgumentNullException("array");
    _array = array; 
  }

  public static implicit operator Int32ArrayWithOperators(int[] array) {
    return new Int32ArrayWithOperators(array); 
  }
  public static implicit operator int[](Int32ArrayWithOperators wrapper) {
    return wrapper._array;
  }

  public static Int32ArrayWithOperators operator +(Int32ArrayWithOperators left, Int32ArrayWithOperators right) {
    var x = left._array;
    var y = right._array;
    return x.Zip(y, (a, b) => a + b).ToArray();
  }
}

Based on a related post that I wrote.

like image 24
Jordão Avatar answered Oct 25 '22 19:10

Jordão