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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:31:32  来源:igfitidea点击:

Error: Member is inaccessible

c++inheritance

提问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 cardsprotectedinstead of private. This ensures the encapsulation is in place but the method is accessible by all derivative classes.

由于您的类 Deck 继承自 Hand(并且它不是朋友类,也不是方法Deck::shuffle()),您可以简单地用 makecardsprotected代替private。这确保封装到位,但所有派生类都可以访问该方法。

Just take a look, among other references and tutorials, there:

看看其他参考资料和教程,有:

  1. http://www.cplusplus.com/doc/tutorial/inheritance/
  2. http://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/
  1. http://www.cplusplus.com/doc/tutorial/inheritance/
  2. http://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/

回答by Nima Soroush

In case of inheritance (your case) the best solution is to make cardsprotected:

在继承(你的情况)的情况下,最好的解决方案是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;
};