【问题标题】:C++ Inheritance: Calling Parent Class ConstructorC++ 继承:调用父类构造函数
【发布时间】:2015-12-08 19:23:28
【问题描述】:

我正试图记住如何处理继承问题。假设我们有一个名为 Fruits 的父类/基类和一个名为 Apples 的子类/派生类。 Apples 与 Fruits 的唯一不同在于它有一个额外的变量,称为数字。我们将如何实现它,以便 Apples 默认始终调用父类构造函数,其值为“Apples”(名称)和 SNACK(类型)?

Fruits 会这样实现(

Fruits::Fruits(string name, KIND type): myName(name), myKind(type)
{}

Apples 是如何实现的,如果 Apples 被称为 Apples(),它的默认名称为“Apples”,类型为 SNACK,编号为 5? 这是正确的吗?

Apples::Apples() : Fruits("Apple", SNACK)
{
    number = 5;
}
 Apples::Apples(int num)  : FoodItem("Pancakes", BREAKFAST )
{

}

【问题讨论】:

  • 你说的是苹果和水果,但我看到的是 Pancake 和 FoodItem。你介意举个例子吗?
  • FruitFoodItem是什么关系?
  • @Arun edit...搞错了!
  • @ohbrobig:谢谢,这就解释了。我已经添加了答案。

标签: c++ class inheritance


【解决方案1】:

这种方式是正确的:

Apples::Apples() : Fruits("Apple", BREAKFAST)
{
    number = 5;
}

但这种方式会更好,因为它更具可读性和一致性:

Apples::Apples() : Fruits("Apple", BREAKFAST), number( 5 )
{
}

【讨论】:

    【解决方案2】:

    我会试试这些:

    // Default value for number
    Apples::Apples() : Fruits("Apple", SNACK), number(5)
    {
    }
    
    // Caller specified value for number
    Apples::Apples(int num)  : FoodItem("Pancakes", BREAKFAST), number(num)
    {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2011-12-08
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      相关资源
      最近更新 更多