C++ 错误:成员无法访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17895983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: Member is inaccessible
提问by LazySloth13
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 asstd::vector<Card>& getCards()
or is there another way to avoid the error.
我是否应该只包含一个函数,例如std::vector<Card>& getCards()
或者 是否有另一种方法来避免错误。
采纳答案by Ahmed Masud
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);
};
回答by Nicholas
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.
由于您的类 Deck 继承自 Hand(并且它不是朋友类,也不是方法Deck::shuffle()
),您可以简单地用 makecards
protected
代替private
。这确保封装到位,但所有派生类都可以访问该方法。
Just take a look, among other references and tutorials, there:
看看其他参考资料和教程,有:
回答by Nima Soroush
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;
};