The following code demonstrate simple operator overloading:
Class Position has 3 int field and a method to print them.
class Position
{
private:
int x,y,z;
public:
void print()
{
cout << x << "," << y << "," << z << endl;
}
Position (int a, int b, int c)
: x(4),
y(50),
z(23)
{
x=a;
y=b;
z=c;
}
Position operator+(const Position &other);
Position operator*=(const int &multi);
};
Operators + and *= are overloaded as such:
Position Position::operator+ (const Position &other)
{
x = x + other.x;
y = y + other.y;
z = z + other.z;
return *this;
}
Position Position::operator*= (const int &multi)
{
x = x * multi;
y = y * multi;
z = z * multi;
return *this;
}
The code runs:
int main()
{
Position p5( 1, 2, 3 );
p5.print();
Position p6( 4, 5, 6 );
p6.print();
Position p7 = p5 + p6;
p7.print();
p7 *= 2;
p7.print();
(p7 *= 2) *= 3;
p7.print();
}
The result yielded are:
1,2,3
4,5,6
5,7,9
10,14,18
20,28,36
Question is why won't the last result perform as it should when it is done in nested?