Sign in to follow this  

[C++]overloading += error

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

If you intended to correct an error in the post then please contact us.

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)
		myArray::Add(ppMyArray, m->ppMyArray);
	return this;
}

Matrix& Matrix::operator +=(const Matrix &m) //works fine
{	
	if(x == m.x && y == m.y)
		myArray::Add(ppMyArray, m.ppMyArray);
	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 this post


Link to post
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 this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this