Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 581
Nayef Avatar asked Dec 01 '25 11:12

Nayef


2 Answers

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.
}
like image 65
Cornstalks Avatar answered Dec 03 '25 02:12

Cornstalks


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 
like image 32
Alexey Frunze Avatar answered Dec 03 '25 01:12

Alexey Frunze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!