0

好的,所以这看起来很简单,但是当它不起作用时它会爆炸我的大脑。这是一个非常简单的几个类。(在 VC++ 中)

class Food
{
protected:
    char maxAmountCarried;
};
class Fruit:Food
{
protected:
     Fruit()
     {
         maxAmountCarried = 8; // Works fine
     }
};
class Watermelon:Fruit
{
protected:
     Watermelon()
     {
          maxAmountCarried = 1; //Food::maxAmountCarried" (declared at line 208) is inaccessible
     }
};

所以基本上,我希望水果的最大承载能力默认为 8。西瓜要大得多,所以容量改为 1。但是,不幸的是我无法访问该属性。

如果有人能告诉我解决这个问题的方法,那将是非常有帮助的。

提前致谢 :)

4

1 回答 1

3

在 C++ 中,当class用作类键来定义类时,继承默认是私有的。如果你想要公共继承,你必须说:

class Fruit : public Food { /* ... */ };

class Watermelon : public Fruit { /* ... */ };

否则,在 中Food::maxAmountCarried变为私有Fruit且无法从 中访问Watermelon

于 2013-10-22T13:19:05.017 回答