C++ Without Fear (Pioneer Panel's Library) by Brian Overland

C++ Without Fear (Pioneer Panel's Library) by Brian Overland

Author:Brian Overland
Language: eng
Format: epub
Publisher: Prentice Hall
Published: 2011-03-24T16:00:00+00:00


Introducing the Fraction Class

One of the best ways to think about object orientation is to consider it a way to define useful new data types. A class becomes an extension to the language itself. A perfect example is a Fraction class (which could also be called a “rational number” class) that stores two numbers representing a numerator and denominator.

The Fraction class is useful if you ever need to store numbers such as 1/3 or 2/7 and need to store them precisely. You also even use the class to store dollar-and-cents figures, such as $1.57.

In creating the Fraction class, it becomes especially important to restrict access to the data members, for several reasons. For one thing, you should never allow a 0 denominator, because the ratio 1/0 is not a legal operation.

And even with legal operations, it’s important to simplify ratios so that there’s a unique expression of every rational number. For example, 3/3 and 1/1 specify the same quantity, as do 2/4 and 1/2.

In the next few sections, we’ll develop functions that automatically handle all this work. Users of the class will be able to create any number of Fraction objects, and operations such as the following will do the right thing “automagically.”

Fraction a(1, 6); // a = 1/6

Fraction b(1, 3); // b = 1/3



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.