// Die.h Dave Reed (based on code by Owen Astrachan) // davereed@creighton.edu // // A class for simulating an N-sided die. // // Die(int sides) -- constructor, with the number of die sides specified // (a default value of 6 is assumed if not specified) // int Roll() -- returns the random "roll" of the die, a uniformly // distributed random number between 1 and # sides // int NumSides() -- access function, returns # of sides // int NumRolls() -- access function, returns # of times Roll called // for that particular Die #ifndef _DIE_H #define _DIE_H #include class Die { public: Die(int sides = 6); int Roll(); int NumSides() const; int NumRolls() const; private: int myRollCount; // # times die rolled int mySides; // # sides on die static bool ourInitialized; // for 'per-class' initialization }; ///////////////////////////////////////////////////// bool Die::ourInitialized = false; Die::Die(int sides) // Results: all private fields are initialized { if (!ourInitialized) { ourInitialized = true; // only call srand once srand(unsigned(time(0))); // randomize } myRollCount = 0; mySides = sides; } int Die::Roll() // Returns: a random 'die' roll (and roll count is incremented) { int dieRoll = int(rand()) % mySides + 1; myRollCount++; return dieRoll; } int Die::NumSides() const // Returns: # of sides on the die { return mySides; } int Die::NumRolls() const // Returns: # of times the die has been rolled { return myRollCount; } #endif /* _DIE_H not defined */