//===Dice.h=====================
#include
#include
// helper function used to initialize th
// e random number generator
// by using an function external to the
// class, we ensure that the static variabl
// e it
// uses to track whether srand has been
// yet or not, is never in an undefined sta
// te
void InitializeRandomizer();
class Dice
{
private:
// by making this private it prevents the use of a constructor with no parameters
Dice();
protected:
int value;
public:
// will generate a random number between 1 and upper
// could of used the (int lower, int upper) constructor with a default parameter,
// but it would of added extra code which would be less efficient and it would also
// of reversed the order of the parameters to (int upper, int lower=0) which is
// counter-intuitive
Dice(int upper)
{
InitializeRandomizer();
value = (static_cast
}
// will generate a random number between lower and upper
Dice(int lower, int upper)
{
InitializeRandomizer();
upper -= (lower - 1);
value = (static_cast
}
// allows objects of the class to be treated as if they were ints, which in the case
// of this class makes alot of sense
operator int() const
{
return value;
}
};
//===Dice.cpp===================
#include "Dice.h"
// function used to seed the random numb
// er generator
// one possible side-effect of this is i
// f a program creates it's first Dice obje
// ct after it
// has set the seed to a particular valu
// e, the random number generator will be r
// eseeded to
// a different (except in the fluke wild
// chance that the numbers match)
void InitializeRandomizer()
{
// used to determine if srand has already been run once
// since it is static it will remain the same for as long as the program runs
static bool initialized = false;
// if it hasn't been initialized, do so now
if(! initialized)
{
// this function initializes the random number generator
srand( (unsigned)time( NULL ) );
// set initialized to true to prevent further initializations
initialized = true;
}
}
//===main.cpp===================
// Sample program using Dice class
#include
#include
#include "dice.h"
using std::cout;
using std::endl;
int main(int argv, char* argc[])
{
int numberOfRolls=10;
if(argv > 1)
{
numberOfRolls = atoi(argc[1]);
}
int total = 0;
for(int i=0; i < numberOfRolls; ++i)
{
int roll = Dice(6)+Dice(6)+Dice(6);
cout << "Roll " << i << ": " << endl;
total += roll;
}
cout << "Total of all rolls: " << total << endl;
return 0;
}