Overloading Binary and Assignment Operators in Vector Class
martianxx (42)
Feb 5, 2013 at 6:26pm UTC
Hi,
I am making a vector class and am having some problems creating the overloaded arithmetic operators and assignment operators.
Here is an example of my "+=" code as it stands the errors are similar/the same for the other operators except "=" operator which works fine:
1 2 3 4 5 6
Vector3& Vector3::operator +=(const Vector3 &rhs)
{
Vector3 tmp = *this ;
Set(tmp.getX() + rhs.getX(), tmp.getY() + rhs.getY(), tmp.getZ() + rhs.getZ());
return *this ;
}
I have tried a lot of different approaches ad always get the error:
error: passing 'const Vector3' as 'this' argument of 'double Vector3::getX()' discards qualifiers
error: passing 'const Vector3' as 'this' argument of 'double Vector3::getY()' discards qualifiers
error: passing 'const Vector3' as 'this' argument of 'double Vector3::getZ()' discards qualifiers
Anyone know why this is? I am guessing it is something pretty simple that I am missing.
Thanks.
defaultplayer (6)
Feb 5, 2013 at 6:35pm UTC
The error message looks like getX/Y/Z are not declared const, so you are not allowed to call them on a const instance, in this case rhs.
Last edited on Feb 5, 2013 at 6:35pm UTC
cire (2354)
Feb 5, 2013 at 6:38pm UTC
rhs is a const object. getX , getY and getZ don't operate on const objects (as they should.)
Solution: change the definition of Vector3, so that getX , getY and getZ do operate on const objects.
1 2 3 4 5
class Vector3 {
// ...
int getX() const ;
// ...
};
Last edited on Feb 5, 2013 at 6:38pm UTC
martianxx (42)
Feb 5, 2013 at 7:09pm UTC
I assumed that that couldn't be the problem because I was sure I had declared the getX etc to be const but I look there and you're right I had forgotten to do it. Thanks for the quick response.
L B (3816)
Feb 5, 2013 at 7:34pm UTC
Is there any particular reason you are forwarding access to X/Y/Z with getters and setters? It seems pointless in this case.
martianxx (42)
Feb 6, 2013 at 11:31am UTC
Because I plan to use operators ([]) to access them later and just made these temporarily.