in c++ how can I abstract a 6 sided die in one class called Die.then do the foll
ID: 3847015 • Letter: I
Question
in c++ how can I abstract a 6 sided die in one class called Die.then do the following
Explanation / Answer
//Die.h
class Die
{
short val; //for storing current throw value.
public:
Die(void);
~Die(void);
int RollDie();
};
//Die.cpp
#include "Die.h"
#include <stdlib.h>
#include <iostream>
Die::Die(void) //constructor
{
val = 1; //initial value 1
}
Die::~Die(void)
{
}
int Die::RollDie()
{
val = rand() % 6 + 1; //random number to get val b/w 1 to 6
return val;
}
//DiceCup.h
#pragma once
#include "Die.h"
#include <vector>;
class DiceCup
{
int numberOfDiceInCup; //no. of dices , set in the c'trct
std::vector<int>sumResultList; //sum of dice throw
Die *dice; //point to dice objects
public:
int ReportSum(int X);
DiceCup(int numberOfDice);
~DiceCup(void);
void Throw();
};
//DiceCup.cpp
#include "StdAfx.h"
#include "DiceCup.h"
DiceCup::DiceCup(int numberOfDice)
{
numberOfDiceInCup = numberOfDice;
dice = new Die[numberOfDice]; //create objs arrays
}
DiceCup::~DiceCup(void)
{
delete[] dice;//delete objs arrays
}
void DiceCup::Throw() //A single throw
{
int sum = 0;
for(int i=0; i < numberOfDiceInCup; i++)
{
sum+=dice[i].RollDie(); //call roll die function for each die and get result.
}
sumResultList.push_back(sum);
}
int DiceCup::ReportSum(int X) //Report the sum
{
int count = 0;
for(std::vector<int>::iterator itr = sumResultList.begin(); itr!=sumResultList.end(); itr++)
{
if ( *itr == X )
count++;
}
return count;
}
//main.cpp
#include <iostream>
#include "DiceCup.h"
int main()
{
DiceCup diceCup(3); //three dices
for(int i=0; i<200; i++) //Test case
{
diceCup.Throw();
}
int sum=0;
std::cout<<" Enter the sum to be reported: ";
std::cin>>sum;
std::cout<< " Sum "<<sum<<" came "<<diceCup.ReportSum(sum)<<" times.";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.