CS12,
Lab 2
Lab
Cycle of April 19--23
Topics:
·
Friend functions
·
Overloading the insertion operator (<<) for output
·
Static class members and static member functions.
In this lab you will be modifying the Dice class from lab 1 to
Enhance its usability.
You will be adding a friend function to overload the <<
operator. This will perform a function similar to the method roll(),
but instead of returning the result of the roll, it will print it out.
In addition, you will add a static class member that will keep track of
the number of Dice objects in existence in the program.
To do:
·
Copy the files dice.h and dice.cpp, which contain the Dice
class.
·
Add an overloaded operator<< as a friend function of the
class. The function should be defined in dice.h and implemented in
dice.cpp. Do not forget to update my_rolls in the function. The
overloaded operator should take an ostream reference object as a parameter and
return a reference to an ostream.
·
Add a static data member num_dice which will contain the
number of Dice objects in existence
·
Initialize num_dice properly in dice.cpp
·
Add appropriate code to the constructor and destructor
that will update num_dice.
·
Add a static method numDice() which will return the
number of Dice objects in the program.
·
Write a main() that will test both enhancements you made
to the Dice class. It should declare a few Dice objects, check how many
are in existence using the numDice() method, and also print out the
result of rolling one of the dice using cout << my_d; instead of
my_d.roll(); (assume my_d is a declared Dice object).
Extra credit:
·
The main program creates objects and uses numDice() to
count them. It does not check whether num_dice is appropriately
decreased when an object ceases to exist, because the objects you
declared are only destructed at the end of main(), as the last thing
done by the program. How would you test if
num_dice is decreased correctly? Design a short program to test this
and write it.