We have encountered a very similar problem to this before.
There are times when GCC will restrict how we can access the variable returned
from a function/expression.
As the OP says, the code above will compile on MSVC but not GCC.
The problem lies with the assignment operator: (which isn't written quite right)
1 2 3 4 5 6 7 8
|
Vector Vector::operator = (Vector &p)
{
setX(p.getX());
setY(p.getY());
setZ(p.getZ());
return *this;
}
|
and the line
vect3 = vect2 - vect1;
.
The result of the subtraction operator is a (un-named) value Vector variable - and
GCC will not let us take us take a plain old reference to this variable (but MSVC will).
We can re-write the assignment like this:
(Notice that we are now passing by value rather than by reference)
1 2 3 4 5 6 7 8
|
Vector Vector::operator = (Vector p)
{
setX(p.getX());
setY(p.getY());
setZ(p.getZ());
return *this;
}
|
This will compile but is not the correct way to write the assignment operator.
The assignment opertator should be setup like this (as already said by
wooyen
1 2 3 4 5 6 7 8
|
Vector& Vector::operator = (const Vector &p)
{
setX(p.getX());
setY(p.getY());
setZ(p.getZ());
return *this;
}
|
GCC will let us have the constant reference.
However, this will raise some other problems - now that our parameter
is constant, GCC will raise errors with the
getX(), getY(), getZ() functions.
These functions have not been declared and defined as constant functions,
so GCC will not allow them to operate on a constant object.
We know that they do not change the object (and do not need to change) the object, so they can be changed to be constant functions.
(Anyway, when you are inside a class function - there is no point in using the
Get functions - because you have access to all the class/object variables directly. Using the
Get functions is just adding overhead).
1 2 3 4 5 6 7
|
Vector& Vector::operator = (const Vector &p)
{
x=p.x;
y=p.y;
z=p.z;
return *this;
}
|
**BTW - as
wooyen said - your inheritance structure is not good**