Nayef
Nayef

Reputation: 374

Overload operator '+' to add two arrays in C++

I want to add two arrays by simply writing:

int a[4] = {1,2,3,4};
int b[4] = {2,1,3,1};
int sum[4] = a + b;

I wrote this function but I got an error

int* operator+(const uint32& other) const{
    uint32 sum[n];
    for(int i=0; i<n; i++){
        sum[i] = (*this[i]) + other[i];
    }
    return sum;
}

Could you help me on this? Thanks in advance.

Upvotes: 2

Views: 18841

Answers (7)

Cornstalks
Cornstalks

Reputation: 38228

Let's go through your code, piece by piece, and look at the problems:

int* operator+(const uint32& other) const{
  1. You can't overload operators for built-in types, so this is doomed from the beginning
  2. Even if you could do this (which you can't), it needs to take two parameters since it's non-member binary function.
    uint32 sum[n];
  1. You can't make variable-length arrays in C++ (assuming n isn't a compile-time constant) (note: G++ has some extensions that allow this, but it's non-standard C++)
    for(int i=0; i<n; i++){
        sum[i] = (*this[i]) + other[i];
  1. There's no this pointer to begin with in this code (it's not a member function)...
  2. const uint32& other is not an array/pointer to an array. It's a single reference to a single uint32. That means that other in this code is not an array/pointer to an array, and so you cannot do other[i] (it's like trying to do int x = 3; x[4] = 13;, which makes no sense).
    }
    return sum;
  1. You're returning a pointer to a locally allocated array, which means this will result in undefined behavior, as the memory associated with sum is going to get annihilated when this function returns.
}

Upvotes: 11

Alexey Frunze
Alexey Frunze

Reputation: 62086

This is probably wrong, but it appears to work (C++11):

#include <iostream>
#include <array>

using namespace std;

template <class T>
T operator+(const T& a1, const T& a2)
{
  T a;
  for (typename T::size_type i = 0; i < a1.size(); i++)
    a[i] = a1[i] + a2[i];
  return a;
}

int main()
{
  array<int,5> a1 = { 1, 2, 3, 4, 5 };
  array<int,5> a2 = { 2, 3, 4, 5, 6 };
  array<int,5> a3 = a1 + a2;

  for (int i = 0; i < 5; i++)
    cout << a1[i] << '+' << a2[i] << '=' << a3[i] << ' ';

  cout << endl;
  return 0;
}

Output (ideone):

1+2=3 2+3=5 3+4=7 4+5=9 5+6=11 

Upvotes: 3

51k
51k

Reputation: 1443

first is your code getting compiled properly, you have used 'n' directly in declaring array, is 'n' declared as constant.. And moreover you have taken a local variable in the function and returning it, well, this return a garbage form the stack, wat i can suggest is you malloc some memory and use it,, but again freeing it would be needed...

Hey, what you could do is,

Take a wrapper class "array"

class array
{
   int *ipArr;
   DWORD size;
};

then in constructor you can pass the size you want to have an array of

array(DWORD dwSize);
{
  // then malloc memory of size dwSize;
}

Have an overloaded operator'+' for this class, that will have the above implementation of adding two int arrays, Note here you will also need to overlaod the '=' assignment operator, so that our array class can you is directly.. now you can free the associated memory in the destructor

Upvotes: 1

Dominique McDonnell
Dominique McDonnell

Reputation: 2520

You have a few problems. The first is that you aren't passing in both arrays, and then you don't specify what n is, and the last is that you are trying to pass out a pointer to a local variable. It looks like you are trying to make a member operator of a class.

So basically you are trying to add the contents of an unspecified length array to an uninitialised array of the same length and return the stack memory.

So if you pass in pointers to the arrays and the length of the array and an output array then it would work, but you wouldn't have the syntax

sum = a + b; 

it would be something like

addArray(&a, &b, &sum, 4);

To get the syntax you want you could make a class that wraps an array. But that is a much more complicated task.

Upvotes: 0

You cannot overload operators for types other than your own defined types. That is, if you create a class X, you can overload operators for X, but you cannot overload operators for arrays or pointers to fundamental types.

Upvotes: 1

Nikos C.
Nikos C.

Reputation: 51880

You cannot do that. Non-member binary operators must take two arguments (you only provided one), so you could try this:

int* operator+(const uint32& a, const uint32& b)

But that can't possibly work either, since you want to add arrays, not single uint32 variables. So you would think that this would do it:

int* operator+(const uint32[] a, const uint32[] b)

or:

int* operator+(const uint32[4] a, const uint32[4] b)

But no go. It's illegal because you cannot have pointer types as both arguments in an operator overload. Additionally, at least one of the arguments must be a class type or an enum. So what you're trying to do is already impossible on at least two different levels.

It's impossible to do what you want. One correct way to go about it is to write your own class for an array that can be added to another one.

Upvotes: 2

john.pavan
john.pavan

Reputation: 950

I think the issue is that you're missing a way to pass in the length of the array. You might need to do something a bit more sophisticated. Something like:

class AddingVector : public std::vector<int>
{
    public:
    typedef AddingVector type;
    type operator+(const AddingVector& rhs, const AddingVector& lhs)
    {
       /* validate that they're the same size, decide how you want to handle that*/
       AddingVector retVal;
       AddingVector::const_iterator rIter = rhs.begin();
       AddingVector::const_iterator lIter = lhs.begin();
       while (rIter != rhs.end() && lIter != lhs.end()) {
         retVal.push_back(*rIter + *lIter);
         ++rIter;
         ++lIter;
       }
       return retVal;
     }
}

Upvotes: 2

Related Questions