C++ 修改基类的属性
C++ Modifying properties from a base class
好吧,这看起来很简单,但当它不起作用时,它会爆炸我的大脑。这里有一个非常简单的几个类。(顺便说一句,在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::maxAmountCarried
在Fruit
中变为私有,并且无法从Watermelon
内访问。
相关文章:
- 基类需要派生类属性
- 使用基类的C++和修改私有/受保护的属性
- 子类中具有不同值的静态基类属性
- 即使基类属性在完成向下转换时是虚拟的,是否有效
- 继承:派生类的基类属性可访问性
- 通过"a pointer of the base class"访问未在基类中声明的子类的方法或属性(动态)
- 基类如何知道其派生类的属性
- C++基类指针容器中,编辑特定对象的属性
- C++引用基类中的子类指针属性
- C++派生类的设置属性到从同一基类派生的未知类对象
- C++:新的基类,但它可以访问派生类的属性
- C++-填充派生类数据成员,同时设置基类属性值
- C++ 修改基类的属性
- 从基类指针比较模板化子类的属性
- 是否可以在初始化列表中使用基类属性
- 如何在C++中从基类访问派生类的属性
- 基类作为属性
- 使用派生类"istream"读取基类的属性
- 实现基类方法来访问派生类的属性
- 如何使用指向基类c++的指针在派生类中创建属性