So, for my c++ course, I am trying to make a "Calculator" class that is basically teaching us how to overload operators and organize a basic class.
my class only contains one private variable so far, called screen, which is holding the number which is having the arithmetic being applied to it.
my problem is that the arithmetic is not being applied correctly in the line ((((a+3.12)+5)-2)*3)/5;
my output is only 3.12, so it is only doing the a+3.12 in the innermost parenthesis
I suspect that this may be because I am not returning the object from the operator overload function correctly. Any help would be greatly appreciated
Unfortunately, I cannot change that line, as it was given with the assignment and I need to make my class work with how it is.
I am not sure how I can make it work with ((((a+3.12)+5)-2)*3)/5;
Here is how I understand my code, which must be incorrect since I dont understand why its not working as I expect:
a+3.12 ----->when the + operator is seen with a double on the right side, it goes into my +operator function, which adds the double value to screen, then the object(with updated screen) is returned to main
now, that line is more like (((a+5)-2)*3)/5; with a being the object returned by the first operation
and the rest of the arithmetic would behave similarly...is this not how the object is being returned to main?
a+3.12 ----->when the + operator is seen with a double on the right side,
> it goes into my +operator function, which adds the double value to screen,
Yes.
> then the object(with updated screen) is returned to main
No. Then a copy of the object (with updated screen) is returned to main. main() then performs the next operation on this copy instead of on the original 'a' object.
Return the object instead of a copy, and you would get the behaviour that you expect.
Your operators return a copy of the object, so it's more like a+3.12 gets evaluated and then you have (((copy_of_a+5)-2)*3)/5, and because you have no way to access those temporary objects, the results of the calculation are lost.
Unfortunately, I cannot change that line, as it was given with the assignment and I need to make my class work with how it is.
That is unfortunate. I would verify with your instructor that you understand the assignment correctly, because that is certainly not the way one would normally implement those operators.