This topic is 3679 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I'm trying to overload +=, -= and *= using pointers.
Matrix* Matrix::operator +=(const Matrix *const m)
{
if(x == m->x && y == m->y)
return this;
}

Matrix& Matrix::operator +=(const Matrix &m) //works fine
{
if(x == m.x && y == m.y)
return *this;
}


The second function works fine, but I'll be working with pointers so I need the first one. I get: 1>c:\users\user\documents\visual studio 2008\projects\matrices\matrices\main.cpp(11) : error C2297: '+=' : illegal, right operand has type 'Matrix *' 1>c:\users\user\documents\visual studio 2008\projects\matrices\matrices\main.cpp(11) : error C2114: '+=' : pointer on left; needs integral value on right

##### Share on other sites
You cannot provide operator overloads where both operands have primitive type. Pointers have primitive type.

##### Share on other sites
To add to what Sneftel said, at least one operand must be a user defined class, struct or enum.

##### Share on other sites
It looks like you're trying to write expressions of the form '(Matrix*) += (Matrix)', and expecting the '(Matrix) += (Matrix*)' operator overload to cover that. This doesn't work because even if the language expected addition to be commutative (it doesn't), operator+= is something fundamentally different from operator+ (operator+= modifies the left-hand side to become equal to the sum; operator+ leaves both values untouched and returns the sum). Really, overloading operator+= to return anything other than a (possibly const) reference to the left-hand-side type is a bad idea. (Or possibly void; but non-const reference is the usual option - it allows for operator chaining to work the same way with the class as it would with primitive types.)

Quote:
 The second function works fine, but I'll be working with pointers so I need the first one.

This is fundamentally incorrect anyway. All you need to do is dereference the pointer before performing the addition:

Matrix *x, *y;Matrix a, b;// ...*x += *y;a += *x;*y += b;

Don't worry, this will modify the objects as expected, and not make temporary copies, modify those and throw them away. In effect, the return type of dereferencing pointer-to-T is reference-to-T. :)

##### Share on other sites
Thanks for the help!

1. 1
2. 2
3. 3
Rutin
15
4. 4
khawk
13
5. 5

• 9
• 9
• 11
• 11
• 23
• ### Forum Statistics

• Total Topics
633665
• Total Posts
3013241
×