[英]Error: Member is inaccessible
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: shuffle()
函数的声明如下:
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. 我应该只包括std::vector<Card>& getCards()
类的函数,还是有另一种避免错误的方法。
You can declare cards as protected
: 您可以将卡片声明为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
. 由于您的Deck类是从Hand继承的(它不是一个朋友类,也不是Deck::shuffle()
),因此您可以简单地使cards
protected
而不是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: 在继承的情况下(您的情况),最好的解决方案是对cards
保护:
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.