【问题标题】:C++ Modifying properties from a base classC++ 修改基类的属性
【发布时间】:2013-10-22 13:16:20
【问题描述】:

好的,这看起来很简单,但当它不起作用时,它会让我的大脑爆炸。 这是一个非常简单的几个类。 (在 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。 但是,很遗憾我无法访问该属性。

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

提前致谢:)

【问题讨论】:

  • interface 不是有效的 C++ 关键字。
  • 也不会省略分号。
  • 糟糕,对不起!实际上并没有复制和粘贴代码(这显然只是一个类比)所以我犯了几个错误=S

标签: c++ inheritance properties interface


【解决方案1】:

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

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

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

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

【讨论】:

  • 哦,好吧。非常感谢! :)
猜你喜欢
  • 2018-10-17
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多