[英]C++ Modifying properties from a base class
Okay so this seems so simple and yet it explodes my brain when it doesn't work. 好的,这看起来很简单,但是当它不起作用时,它会炸毁我的大脑。 Here's a very simple few classes.
这是一个非常简单的几个类。 (In VC++ btw)
(在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
}
};
So basically, I wanted fruit, by default, to have a max carrying capacity of 8. Watermelons are much larger so the capacity is changed to 1. However, unfortunately I can't access the property. 因此,基本上,我希望默认情况下,水果的最大承载能力为8。西瓜要大得多,因此承载能力更改为1。但是,不幸的是,我无法访问该属性。
It would be so much help if someone could tell me a way to work around this problem. 如果有人可以告诉我解决此问题的方法,那将有很大帮助。
Thanks in advance :) 提前致谢 :)
In C++, when using class
as the class key to define classes, inheritance is private by default. 在C ++中,当使用
class
作为类键来定义类时,默认情况下继承是私有的。 If you want public inheritance, you have to say: 如果要公共继承,则必须说:
class Fruit : public Food { /* ... */ };
class Watermelon : public Fruit { /* ... */ };
Otherwise, Food::maxAmountCarried
becomes private in Fruit
and is not accessible from within Watermelon
. 否则,
Food::maxAmountCarried
在Fruit
变为私有 ,并且无法从Watermelon
内部访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.