C++ 修改基类的属性

C++ Modifying properties from a base class

本文关键字:属性 基类 修改 C++      更新时间:2023-10-16

好吧,这看起来很简单,但当它不起作用时,它会爆炸我的大脑。这里有一个非常简单的几个类。(顺便说一句,在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。但是,不幸的是我无法访问该物业。

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

提前致谢:)

在C++中,当使用 class 作为类键来定义类时,默认情况下继承是私有的。想要公有继承,就得说:

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

否则,Food::maxAmountCarriedFruit中变为私有,并且无法从Watermelon内访问。