0
101 Jan 11, 2009 at 00:02

I do not know how to explain this really. I can not get operators to work when the argument is being returned by another overloaded function.

When I try to run the code, I get:

asdman@asdman-laptop:~\$ g++ op.cpp
op.cpp: In function 'int main()':
op.cpp:21: error: no match for 'operator+=' in 'c += operator+(((Vector&)(& a)), ((Vector&)(& a)))'
op.cpp:8: note: candidates are: void operator+=(Vector&, Vector&)


And here’s the actual source code:

#include <iostream>

struct Vector {
int x,y;
};

// Prototypes
void operator+=(Vector &a, Vector &b);
Vector operator+(Vector &a, Vector &b);

int main() {

Vector a={ 10,-2 };
Vector b={1,4};

std::cout << "Vector a is at (" << a.x << "," << a.y << ")." << std::endl;
std::cout << "Vector b is at (" << b.x << "," << b.y << ")." << std::endl;

Vector c={0,0}; c += (a+a); // <- This does not seem to work.

std::cout << "a + a equals in c, which is at (" << c.x << "," << c.y
<< ")." << std::endl;

return 0;
}

void operator+=(Vector &a, Vector &b) {
a.x +=b.x;
a.y+=b.y;
}

Vector operator+(Vector &a, Vector &b){
Vector c; // A return vector;
c.x = a.x+b.x;
c.y = a.y+b.y;
return c;
}


However, I am not entirely sure whether or not the actual problem lies in the struct or in the overloading part. Actually, I am completely clueless.

Any help appreciated! :)

#### 4 Replies

0
139 Jan 11, 2009 at 00:45

There are two problems here.

First, the operator +=, and all assignment operators, have to return a reference to the object that was assigned to. This is because in C++ you can chain assignments, like a = b = c, which is parsed as a = (b = c), with ‘a’ getting the result of the assignment ‘b = c’. Similarly you can do a = b += c, etc.

Second, you are using a non-const reference for the ‘b’ parameter to the operator, which means the argument has to be an l-value (for instance a variable). It does not work to pass an expression like ‘(a + a)’ to this operator, since the result of ‘(a + a)’ is a temporary Vector that is not an l-value. Making the parameter a const reference, however, allows you to use temporary objects freely.

So it should work if you write the operator like this:

Vector& operator+=(Vector &a, const Vector &:) {
a = a + b;
return a;
}

0
101 Jan 11, 2009 at 00:50

Thank you, problem solved! Works well. :)

Edit: So, use const whenever possible? E.g. when the data is not being manipulated?

0
101 Jan 11, 2009 at 15:33

@Reedbeta

First, the operator +=, and all assignment operators, have to return a reference to the object that was assigned to.

Actually, no, but it is common practice as the built-in operators do that as well.

0
139 Jan 11, 2009 at 19:07

Ahh, okay, good to know.