2015-12-08 67 views
0

我正在靠墙试图记住如何处理继承。假设我们有一个名为Fruits的父类/基类,以及名为Apples的子类/派生类。苹果只有不同于水果,因为它有一个额外的变量,称为数字。我们将如何实现它,以便默认情况下始终调用父类构造函数,并使用值“Apples”(名称)和SNACK(类型)?C++继承:调用父类构造函数

水果将被实现为这样的(

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

如何将苹果来实现,这样,如果苹果称为苹果()则默认名称为“苹果”和型零食,具有数〜5 ? 这是正确的

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

} 
+1

请您谈一下苹果和水果,但我看到的是煎饼和FoodItem。你想介绍一下你的例子吗? – SergeyA

+0

'Fruit'和'FoodItem'之间的关系是什么? – Arun

+0

@Arun编辑...犯了一个错误! – ohbrobig

回答

1

这种方式是正确的:?

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

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

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

我会尝试这些:

// 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) 
{ 
}