简体   繁体   English

子类也将从其父类的超类继承吗?

[英]Will a subclass also inherit from the super class of it's parent?

Let's say I have a class named Food , a subclass of it named Chicken , then a subclass of the latter which is named Fillet . 假设我有一个名为Food的类,它的子类为Chicken ,然后是后者的子类Fillet Will the Fillet class also inherit from the Food class? 圆角类也将从Food类继承吗? Also, is it right to call Fillet as another subclass of the Food class? 另外,将Fillet称为Food类的另一个子类是否正确?

Simple answer: Yes, to both questions. 简单回答:是的,两个问题都对。 Every subclass inherits all behavior and methods from all its parents (if they're visible). 每个子类都从其所有父级(如果可见)继承所有行为和方法。

it depends on access specifiers private , public , protected . 它取决于访问说明符的私有公共受保护的 All public members of Food will be inherited by Fillet . Food所有公共成员将由Fillet继承。

I think source code will help you a lot. 我认为源代码将对您有很大帮助。

class base 
{
    public:
        int x;
    protected:
        int y;
    private:
        int z;
};

class publicDerived: public base
{
    // x is public
    // y is protected
    // z is not accessible from publicDerived
};

class protectedDerived: protected base
{
    // x is protected
    // y is protected
    // z is not accessible from protectedDerived
};

class privateDerived: private base
{
    // x is private
    // y is private
    // z is not accessible from privateDerived
}

From the documentation ; 文档 ;

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). 除了没有父类的Object之外,每个类都有一个且只有一个直接父类(单继承)。 In the absence of any other explicit superclass, every class is implicitly a subclass of Object. 在没有其他任何显式超类的情况下,每个类都隐式为Object的子类。 Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. 可以从派生自类的类派生类,这些类派生自类,依此类推,并最终派生自最顶层的类Object。 Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object. 据说这样的类是继承链中所有类的后代,并延伸到Object。

So Fillet is a descendant of Food and subclass of Chicken . 因此, FilletFood的后裔,是Chicken子类。

It will inherit explicitly from the super class of its parent depending on access modifiers used in top most class. 它将根据其顶层类中使用的访问修饰符从其父类的超类显式继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM