我有这两个类:
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);
};
Run Code Online (Sandbox Code Playgroud)
当shuffle()函数声明如下:
void Deck::shuffle()
{
std::random_shuffle(cards.begin(), cards.end());
}
Run Code Online (Sandbox Code Playgroud)
但是,这会返回以下错误:
'Hand::cards' : cannot access private member declared in class 'Hand'
Run Code Online (Sandbox Code Playgroud)
我是否应该只包含一个函数,例如std::vector<Card>& getCards()或者 是否有另一种方法来避免错误。
您可以将卡声明为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);
};
Run Code Online (Sandbox Code Playgroud)