【问题标题】:Inheritance: Access both private and public parts of another class继承:访问另一个类的私有和公共部分
【发布时间】:2019-10-21 11:19:19
【问题描述】:

我的作业告诉我在子类中使用父类的私有和公共部分。

但是做类似的事情

class CarInsurance: public Insurance, private Insurance
{
public:
//some stuff...
private:
//some more stuff...
}

是同一个类的重复,这是不可能的。

有没有其他方法可以做到这一点而不必创建多个子类?我只想有一个子类,它可以使用父类的公共和私有部分。

【问题讨论】:

  • 您似乎误解了公共继承与私有继承的含义。私有继承不会授予您访问基类中私有字段的权限。
  • 公有和私有继承与“同时使用父类的私有和公有部分”无关。对我来说,“使用”这个词意味着实际上使用来自父类的成员。而且你根本不能使用基类的私有成员。
  • 您不能访问父类的私有成员,即使在公共继承中也是如此。您必须改为保护父字段。
  • 如果您对作业不确定,请询问您的老师或助教。
  • 从字面上看,它要么要求您使用一些肮脏的技巧(不推荐),要么没有解决方案。子类不能直接访问基类的私有成员

标签: c++ class oop


【解决方案1】:

是的,您可以通过将班级结成朋友来做到这一点。

概念是:

class Insurance
{
// among other things add this line (doesn't matter if its public, protected or private)
friend class CarInsurance;
}

//////////////////////////

class CarInsurance: public Insurance // we need public here
{
public:
//some stuff...
private:
//some more stuff...
}

【讨论】:

  • 因此,一个班级控制着谁可以触摸他们的私处(妈妈,我遵守了新的行为准则!):只有朋友。
猜你喜欢
  • 1970-01-01
  • 2011-03-11
  • 2011-01-05
  • 2014-09-05
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 2011-08-10
相关资源
最近更新 更多