point.h
...
Point operator +=(double & left, const Point & right) {
return Point(left + right.x, left + right.y, left + right.z);
}
// std::ostream is overloaded
...
main.cpp
#include <iostream>
#include "point.h"
int main() {
double a = 1.0;
Point b(1.0, 1.0, 1.0);
a += b;
std::cout << a << std::endl;
}
Output:
1
I would like to return the sum:
(2, 2, 2)
But the double type is preserved by compiler when compound-assignment.
This operator definition
is wrong because it assigns nothing to the left operand and does not return the lvalue of the assigned object.
In general it is better to define such operators as class member functions.
I would define it the following way
As for your code and particularly this statement
then it is not clear whether there is a conversion constructor that converts an object of type double (the type that object a has) to type Point because you did not show the class definition. And as I already pointed out the operator you defined does not change the left operand (a temporary object of type Point that would be created based on the object
a
). So if even the record above is correct in any case the original objecta
will not be changed.For an objects of type double used as the left operand you could define operator + instead of the operator +=.
For example
The details of the implementation for your class can be different because I do not see the class definition. Nevertheless this definition demonstrates the idea.
In this case you could write
and get the expected result