C++ 1) Create a template class to define a die, in which the number of faces of
ID: 3907461 • Letter: C
Question
C++
1) Create a template class to define a die, in which the number of faces of the die is an integer template parameter rather than an argument to a constructor of an individual die. What tradeoffs are there between the two approaches? ("tradeoffs" means pros and cons or advantages and disadvantages)
2) Add a member to the die class to obtain the number of faces of the die. Make this a function. Don't just make the number of faces a public member variable.
3) Add a member function to the die class to obtain the value of the last roll without rolling it again. What else do you need to add to the class to make this feasible?
Explanation / Answer
#include<iostream>
#include<ctime>
#include<stdlib.h>
using namespace std;
class die
{
private:
int numberOfFaces;
int faceValue;
public:
die();
die(int, int);
int roll();
void print();
};
die::die()
{
numberOfFaces=6;
faceValue=1;
}
die::die(int numOfFaces, int faceVal)
{
numberOfFaces=numOfFaces;
faceValue=faceVal;
}
int die::roll()
{
faceValue=rand()%numberOfFaces;
return faceValue;
}
void die::print()
{
cout << faceValue << endl;
}
class pairOfDice : public die
{
private:
die die1;
die die2;
int value1;
int value2;
int total;
public:
pairOfDice();
int roll();
};
pairOfDice::pairOfDice():die(6,1)
{
value1=1;
value2=1;
total=value1+value2;
}
int pairOfDice::roll()
{
value1=die::roll();
value2=die::roll();
total=value1+value2;
return total;
}
int main()
{
int rolls=0,total=0,snakeEyes=0,boxCars=0;
pairOfDice dice;
while(rolls<1000)
{
total = dice.roll();
if(total==2)
snakeEyes++;
else if(total==6)
boxCars++;
else
rolls++;
}
cout<<rolls << " " << snakeEyes << " " <<boxCars<<endl;
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.