I have these two classes:
class Hand
{
public:
int getTotal();
std::vector<Card>& getCards();
void add(Card& card);
void clear();
private:
std::vector<Card> cards;
};
class Deck : public Hand
{
public:
void rePopulate();
void shuffle();
void deal(Hand& hand);
};
Where the shuffle()
function is declared as follows:
void Deck::shuffle()
{
std::random_shuffle(cards.begin(), cards.end());
}
However, this returns the following error:
'Hand::cards' : cannot access private member declared in class 'Hand'
Should I just include a function such as std::vector<Card>& getCards()
or is there another way to avoid the error.
You can declare cards as protected
:
class Hand
{
public:
int getTotal();
std::vector<Card>& getCards();
void add(Card& card);
void clear();
protected:
std::vector<Card> cards;
};
class Deck : public Hand
{
public:
void rePopulate();
void shuffle();
void deal(Hand& hand);
};
Since your class Deck inherits from Hand (and it is not a friend class nor is the method Deck::shuffle()
), you could simply make cards
protected
instead of private
. This ensures the encapsulation is in place but the method is accessible by all derivative classes.
Just take a look, among other references and tutorials, there:
In case of inheritance (your case) the best solution is to make cards
protected:
protected:
std::vector<Card> cards;
But in general you can make them friends.
class Hand
{
friend class Deck;
public:
int getTotal();
std::vector<Card>& getCards();
void add(Card& card);
void clear();
private:
std::vector<Card> cards;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.