









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
How to overload operators in a fraction class to make fraction arithmetic more natural and convenient. The rationale behind overloading the '+' operator and provides code examples for overloading '+' for two fraction objects and for an integer and a fraction object. It also discusses the possibility of overloading other operators and relational operators.
Typology: Slides
1 / 15
This page cannot be seen from the preview
Don't miss anything!










two integer variables designated by numerand denom. These two variables togethersymbolize and contain the rational numberthat we typically think of as numer/denom. For Example:5/2, 3/5, 2/9, 100/3, etc.
B are Fractions, their sum is computed by theexpression C.Add(B); Add is a
non-static method
. C (or always the object to
the left of the dot operator) is the object that callsthe Add method, and B is the argument. Their sumis computed and returned. C and B are notchanged in the call. Review the definition of Add. Why is it not static?
arithmetic with +, -, *, and /, it would be morenatural to write C+B instead of C.Add(B). This is easily accomplished by “overloading”
the + operator for the Fraction class. The next slide shows the overloaded method.
an integer and C is a Fraction? Not yet. But we can add another overloaded
method that will do it.
use one of the Fraction class constructors tocreate a Fraction from N and then use thealready defined overloaded+ for two Fractionobjects. Will this work for C + N? No. But it’s easy to
add a third operator+ that takes a Fraction onthe left and an integer on the right.
Fraction class, we could overload the otherarithmetic operators -, *, and /. In doing so,we could, just as with +, use Sub, Mult, andDiv that have already been written.
static bool
operator<
(Fraction
X,
Fraction
Y)
{
return
X.numerY.denom <Y.numerX.denom);
} Here we use the fact that a/b < c/d if and only if ad<bc, as long
as d and b are positive. (Multiplying both sides of an inequalityby a positive number preserves the inequality.)
must be overloaded in pairs. For example ifyou overload <, you must overload >.Similarly for <= and >=; and == and !=;