Jump to content
  • Advertisement
Sign in to follow this  
sheep19

[C++]overloading += error

This topic is 3627 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
Advertisement
You cannot provide operator overloads where both operands have primitive type. Pointers have primitive type.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!