Case Study: Rational Numbers

In this section, I will discuss another popular example of operator function overloading: a class that encapsulates the implementation of rational numbers (exact fractions) and implements arithmetic operations and comparisons that are supported for integers.

Rational numbers can be represented as two components, the numerator and denominator. They allow the use of operations over fractions without rounding errors, e.g., 1/4 + 3/2 = 14/8 = 7/4.

In the class implementation, the numerator and denominator should be private data members. If the application might be ported to a 16-bit machine, the data members should be of type long. If it will run on 32-bit machines only, data members can be either int or long—on 32-bit ...

Get Core C++ A Software Engineering Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.