+ 2

Can someone please give me some ideas on a program where i can use +,-,* and / when they're overloaded?

operator overloading homework

7th Apr 2017, 8:42 PM
Adiel Cowo
Adiel Cowo - avatar
2 ответов
+ 6
define a Fraction class with numerator and denominator for example tge fraction 1/3 will have 1 as the numerator and 3 as the deniminator then implement the overriden operators
7th Apr 2017, 8:55 PM
Burey
Burey - avatar
+ 1
When you create objects of your own class and you want to be able to do intuitive operations with them, like adding or subtracting; unless they are of a generic type that supports the + operator you can't say myObj = myObj + myObj2, you'll get an error. As to why you'd want o do this, i guess it depends on what you want to do and if you prefer this way instead of using a custom method like .AddNewObject(myObj2) Another reason would be necessity, let's say you have a method/code that gets two or more objects and does some computations with then using basic operators; that works well with Integers and others types that know those operators, but if you want that method to work on objects of your class (your own custom type) then the class has to implement those operators. Think of it like implementing an interface. A funky reason would be to mess with someone, you'd implement​ the + operator to substract or the * operator to add 3.14 one out of ten times, i don't know.. ps: in my playground i have a code that does something similar in python if it helps you understand
7th Apr 2017, 9:06 PM
Eduard Alexandru
Eduard Alexandru - avatar