Programming in C

(Barry) #1
Defining a C++ Class to Work with Fractions 421

The C++ members (instance variables) numeratorand denominatorare labeled
privateto enforce data encapsulation; that is, to prevent them from being directly
accessed from outside the class.
The setNumeratormethod is declared as follows:


void Fraction::setNumerator (int num)


The method is preceded by the notation Fraction::to identify that it belongs to the
Fractionclass.
A new instance of a Fractionis created like a normal variable in C, as in the follow-
ing declaration in main:


Fraction myFract;


The numerator and denominator of the fraction are then set to 1 and 3, respectively,
with the following method calls:


myFract.setNumerator (1);
myFract.setDenominator (3);


The value of the fraction is then displayed using the fraction’s printmethod.
Probably the oddest-appearing statement from Program 19.3 occurs inside the print
method as follows:


std::cout << "The value of the fraction is " << numerator << '/'
<< denominator << '\n';


coutis the name of the standard output stream, analogous to stdoutin C.The <<is
known as the stream insertion operator, and it provides an easy way to get output.You
might recall that <<is also C’s left shift operator.This is one significant aspect of C++: a
feature known as operator overloadingthat allows you to define operators that are associat-
ed with a class. Here, the left shift operator is overloaded so that when it is used in this
context (that is, with a stream as its left operand), it invokes a method to write a format-
ted value to an output stream, instead of trying to actually perform a left shift operation.
As another example of overloading, you might want to override the addition operator
+so that if you try to add two fractions together, as in


myFract + myFract2


an appropriate method from your Fractionclass is invoked to handle the addition.
Each expression that follows the <<is evaluated and written to the standard output
stream. In this case, first the string "The value of the fraction is"gets written,
followed by the fraction’s numerator, followed by a /, the fraction’s denominator, and
then a newline character.
The C++ language is rich with features. Consult Appendix E, “Resources,” for rec-
ommendations on a good tutorial.
Note that in the previous C++ example, the getter methods Numerator ()and
Denominator ()were defined in the Fractionclass but were not used.

Free download pdf