0

Is it possible to overload addition operator(+) for the addition of arrays? Something like:

double operator+ (double a[], double b[])
{
    double c[];

    c[] = a[] + b[];

    return c;
}
1
  • 1
    You're dealing with raw arrays. The problem is that you do not know the size of the array. And "a[] + b[];" doesn't work :) Commented May 29, 2013 at 22:49

5 Answers 5

4

No.

A parameter of type "array of T" is adjusted, at compile time, to type "pointer to T", so your declaration:

double operator+ (double a[], double b[])

really means:

double operator+ (double *a, double *b)

And you can't define an overloaded operator+ for pointer types (at least gcc doesn't think so, and I believe it's correct).

Nor can you declare a function with an array type as its return type; if you try, it's not adjusted to a pointer type, it's just illegal.

You can define functions that take arguments of some container type (std::vector, std::array) -- which is likely to be more useful anyway.

Be sure to think about what your operator+ should do if the left and right operands have different sizes. (Throwing an exception is one reasonable approach.)

Sign up to request clarification or add additional context in comments.

Comments

2

You can't overload global operators taking operands of non-class type. Fortunately there is std::vector<T> (which is of class type) that we can use instead:

#include <vector>
#include <algorithm>
#include <iostream>

template <typename T>
std::vector<T> operator +(std::vector<T> lhs, std::vector<T> rhs)
{
    std::vector<T> temp;
    temp.insert(temp.end(), lhs.begin(), lhs.end());
    temp.insert(temp.end(), rhs.begin(), rhs.end());

    return temp;
}

int main()
{
    std::vector<int> x{1, 2, 3}, y{4, 5, 6};

    std::vector<int> z(x + y);

    for (auto a : z)
        std::cout << a << ' '; // 1 2 3 4 5 6
}

Here is a demo.

6 Comments

I'd make the parameters not need an lvalue.
If you're using C++11 you could also mention std::array.. seems like no one likes/remembers it?
@DyP I would've mentioned it but I had trouble implementing it .
@DyP You're adding the contents of the arrays. I thought the OP was asking to concatenate the arrays...
|
1

Not directly. In principle you can write functions that take (references to) arrays:

// returns a[0]*b[0] + a[1]*b[1] + ... + a[N-1]*b[N-1]
template <int N>
double innerProduct(double const (& a)[N], double const (& b)[N])
{
    double sum = 0;
    for (size_t i = 0; i < N; ++i) sum += a[i] * b[i];
    return sum;
}

But there are several problems:

So either wrap your arrays in a user defined type, or use a regular function (like addInto). For the return value, either pass a result array to be filled as a parameter, or return some other type like std::vector.

Example:

// c[0]=a[0]+b[0]; c[1]=a[1]+b[1]; ... c[N-1]=a[N-1]+b[N-1];
template <int N>
void addInto(double const (& a)[N], double const (& b)[N], double (& out)[N])
{
    for (size_t i = 0; i < N; ++i) out[i] = a[i] + b[i];
}

Comments

1

No you can't. But you can write a class that wraps arrays this way:

#include <iostream>
#include <algorithm>

class Array {
    int* arr;
    int arr_size;

    public:
        Array(int n): arr(new int[n]), arr_size(n) {}
        ~Array(){ delete[] arr; }
        int& operator[](int n) { return arr[n]; }
        Array operator+(Array& other) {
            Array to_return(arr_size);
            for(int i=0 ; i < std::min(arr_size, other.arr_size) ; i++)
                to_return[i] = arr[i] + other[i];
            return to_return;
        }
};

int main() {
    int tmp1[] = {1, 2, 3, 4};
    int tmp2[] = {5, 6, 7, 8};
    Array arr(4), arr2(4);
    for(int i=0 ; i < 4 ; i++) {
        arr[i] = tmp1[i];
        arr2[i] = tmp2[i];
    }
    for(int i=0 ; i < 4 ; i++)
        std::cout << (arr + arr2)[i] << ' ';

    return 0;
}

Output:

6 8 10 12

8 Comments

And with C++11 you can just use std::array.
Your operator+ is going to have problems if the right operand is shorter than the left one. And in the destructor, shouldn't delete arr; be delete[] arr;?
@Keith: See my edited post. Thanks for the observation! (Note: I know the class may not be complete. That was just for demonstration purpose)
I think it really needs a copy-ctor. Otherwise Array to_return = Array(arr_size); will result in two arrays (using the implicitly defined copy ctor) with the same pointer arr. Both deleting it when destroyed -> UB. See Rule of Zero
The line Array to_return = Array(arr_size); creates a temporary and copies it into to_return (though the compiler may elide that copy). If it does not elide the copy, you'll have UB because in that case you have to instances of Array using (and deleting) the same pointer. You could change the line to Array to_return(arr_size);, but the Rule-of-Three problem remains (when you change the line, your program would not contain UB any more).
|
0

It is possible to overload any operator for a class that you write. Keep in mind that operator overloading is only to make code more readable, if your operators do things that aren't very obvious you probably should overload it at all. Also to this specific one you are thinking of you would probably have to write your own wrapper class for arrays. You cannot overload it directly because operator + is already defined for pointers. You may be able to overload operator + for the vector or array datatypes in c++

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.