0
what's the difference?
So if we delete the keyword 'operator+' what's the difference? If you pass Box a and Box b as parameters then the method will still have access to a.Height, b.Height and so on and we will create the new Box object the same way... Right? or not? (and why)
1 Réponse
+ 2
You are right, but miss-interpreted what operator overloading does.
Lets say I didn't overload the operator:
Box add(Box a, Box2 b){
return a.getArea() + b.getArea();
}
// For this example, I'm just adding areas
This is perfectly acceptable.
Now if I want to add them, I can do:
add(Box1, Box2);
Where I'm only adding areas.
However, sometimes it may feel better to use + for addition instead of having to write add.
In that case, you use "operator" to indicate you will be overloading an operator. Followed by the operator itself. "+".
That way, I can write:
Box1 + Box2.
To add the areas.
This is entirely optional of course, which is why some languages don't support it (Like Java). But can be a nice thing for the programmer.
It's essentially nicer for arithmetic.
Lets say I had 2 boxes name a and b.
((a + b * 5) / 3)^2
Would that be easier to read than this?
pow((divide(multiply(add(a, b), 5), 3), 2);
It helps make it like a data-type.