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)
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.
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. 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.