Declare "hand" class as friend of "deck" class.
class hand {
friend class deck;
...
};
Now objects of "deck" class have access to private properties of class "hand" objects.
题
I am making a poker probability program in C++. the program will make a deck, shuffle it, deal five cards and determine what kind of hand you have. This will run 16000 times and estimate the average amount of hands that come up.
I have made three classes, a card class, a deck class, and a hand class. the card class has a character for the suit and an int for the rank, the deck class has a vector of 52 cards which needs to be private, and the hand class has a vector of 5 cards which also needs to be a private member. now the deck class needs to have a dealHand() function which copies the first five cards of the deck into the hand vector, but how could I go about doing this when the hand vector needs to be private and cannot be accessed from the deck class?
this is my deck class
class deck
{
public:
deck();
void shuffle();
hand dealHand();
void printDeck();
private:
vector<card> deckData;
void loadDeck();
};
this is my hand class
class hand
{
public:
hand();
void printHand();
private:
vector<card>handData;
void initHand();
};
and this is the definition for my dealHand function
hand deck::dealHand()
{
hand hand;
for(int j=0; j<5; j++)
{
hand.handData[j].suit = deckData[j].suit;
hand.handData[j].rank = deckData[j].rank;
}
return hand;
}
how could I make this function return an object of the type hand when its member is private?? thank you.
解决方案 3
Declare "hand" class as friend of "deck" class.
class hand {
friend class deck;
...
};
Now objects of "deck" class have access to private properties of class "hand" objects.
其他提示
You need to add a setter for the private members like:
class hand
{
public:
hand();
...
void addCard( suit s, rank r );
...
private:
vector<card>handData;
...
};
void hand::addCard( suit s, rank r )
{
// if you had a constructor for card using suit and rank as parameters
handData.push_back( card( s, r ) );
}
you can just add a giveCard() method to the Hand class, that pushes it back, and at the same time it allows you to check if the hand doesn't already have five cards...