Re: Operator overload not defined error when type is accessed through const struct
That is because the member function was not declared const. If you want to overload operator+ as a member, then I would expect:
Code:
point operator+(const point& right) const
{
return point(x + right.x, y + right.y, z + right.z);
}
Notice the return type is point, not reference to pointer. Notice also the const reference parameter and the const at the end that declares the member function to be const.
Another way is to overload operator+= as a member:
Code:
point& operator+=(const point& right)
{
x += right.x;
y += right.y;
z += right.z;
return *this;
}
then define operator+ as a non-member function in terms of operator+=, e.g.,
Code:
point operator+(point left, const point& right)
{
return left += right;
}
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
Re: Operator overload not defined error when type is accessed through const struct
Originally Posted by Tanaka
This gives me an "operator not defined" error for compilation. How do I fix this, please?
As laserlight pointed out, your return of a reference is wrong here. Even though you don't get a compile error, returning references to local objects is undefined behaviour. For example:
Code:
point& operator+(point& right)
{
return point(x + right.x, y + right.y, z + right.z);
}
You are creating a local "point" object. Then you're returning a reference to this local object. When the operator+ function returns, that local point object is now gone. You now have a reference to something that no longer exists. You now use it in your program, and who knows what will happen -- maybe your program will "work", maybe it will crash, who knows.
The solution as pointed out is to return a point object, not a reference.
Bookmarks