2

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.

Nayef
  • 364
  • 2
  • 8
  • 22
  • What is the error? Generally, `operator+` has a left-hand side and right-hand side (i.e. `int* operator+(const uint32& lhs, const uint32& rhs) const` – RageD Feb 25 '13 at 04:58
  • 1
    Is there some extremely specific reason you can't use `std::vector` or `std::valarray` for this? With the latter, you end up with just `std::valarray a, b, c; /* populate b and c here */ a = b + c;` – Jerry Coffin Feb 25 '13 at 05:05
  • 2
    Also as far as I know, you can't overload operators for non-class or enumerator types. – Rapptz Feb 25 '13 at 05:07

7 Answers7

11

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.
}
Cornstalks
  • 37,137
  • 18
  • 79
  • 144
3

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 
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
2

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;
     }
}
john.pavan
  • 910
  • 4
  • 6
  • 2
    Inheriting from `std::vector` is a no-no. It doesn't have a virtual destructor. – chris Feb 25 '13 at 05:17
  • 2
    Or better yet, just make a [`template const std::vector operator+(const std::vector& lhs, const std::vector& rhs)`](http://ideone.com/RlZEzr) function. Or use `std::valarray`. Also, you've swapped `rhs` and `lhs` so they're on the wrong sides :) – Cornstalks Feb 25 '13 at 05:34
  • 1
    Probably want to make `operator+` a `friend`, but basic concept's worth documenting. chris's quip is a common one, but if the usage is localised enough that you can be confident nobody's going to delete it through a pointer-to-base (which is common enough in one-person few-days/weeks projects) who cares. You're not adding data members so in practice it's safe with every compiler I've ever used anyway, though it's technically undefined behaviour. – Tony Delroy Feb 25 '13 at 07:08
2

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.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • I wrote an update above. I want to update the array a. – Nayef Dec 24 '14 at 10:25
  • 1
    @Nayef Please create a new question for this :-) Editing an old question and changing the subject matter is not a good way to use this site. – Nikos C. Dec 24 '14 at 16:30
  • I did check this question http://stackoverflow.com/questions/27645319/biginteger-class-implementation-overload-operator – Nayef Dec 25 '14 at 07:58
1

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

51k
  • 1,381
  • 3
  • 12
  • 22
1

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.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0

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.

Dominique McDonnell
  • 2,510
  • 16
  • 25