简体   繁体   English

需要继承方面的帮助

[英]Need Help in Inheritance

I have read this question , I still have doubts in my concepts of inheritance.I have tried to solve a homework assignment but I think that I still don't get the access levels. 我已经读过这个问题 ,我仍然怀疑我的继承概念。我试图解决一个家庭作业,但我认为我仍然没有获得访问级别。 I have following questions in my mind, 我脑子里有以下问题,

Is protected and public access specifier same? 受保护的 公共访问说明符是否相同? (I don't find a difference) (我没有发现差异)

My assignment is attached below,please help me out if it is incorrect. 我的作业如下所示,如果不正确,请帮帮我。 在此输入图像描述在此输入图像描述

The difference is that protected members are only visible/accessible to child classes. 不同之处在于受保护的成员仅对子类可见/可访问。

class A {
public:
  int a; // anything can access this member.
private:
  int b; // only A can access this member.
protected:
  int c; // A and every other class that inherits this member can access it.
};

No, they're not the same. 不,他们不一样。

public means that any other class can access the member. public表示任何其他类都可以访问该成员。

private means it's only accessible by it's own class 私有意味着它只能由它自己的类访问

protected means it's accessible by the own class, and all classes derivated from the class protected意味着它可以由自己的类访问,并且所有类都是从类派生的

Example: 例:

class 1 {
    public void do1() { }
    private void do3() { }
    protected void do2 { }

    1()
    {
        public void do1() { } // ok
        private void do2() { } // ok
        protected void do3 { } // ok
    }
}

class 2 {
    2()
    {
        1.do1() { } // ok
        1.do2() { } // ERROR
        1.do3 { } // ERROR
    }
}

class 3 inherits class 1 {
    3()
    {
        do1() { } // ok
        do2() { } // ERROR
        do3 { } // ok = this class can access the the protected member of it's base class
    }
}

You seem to have forgotten the simplest and the most important aspect: Accessibility of members from an unrelated class / in a freestanding (non-member) function. 您似乎忘记了最简单和最重要的方面:来自不相关类/独立(非成员)函数的成员的可访问性。 Public members can be accessed from outside the class and the class hierarchy, private and protected ones cannot. 公共成员可以从类外部访问,类层次结构, 私有和受保护的成员不能。

If you mean public vs protected inheritance , well, the answer is there on your charts. 如果你的意思是公共受保护的 继承 ,那么答案就在你的图表上。

Protected members of a Base class can only be accessed by the Base class and class derived from base class. Base类的受保护成员只能由Base类和从基类派生的类访问。

**Private Members** can be only accesed by its own class and cannot be accesed by the derived class. **私人会员**只能由自己的班级加入,并且不能由派生班级加入。

**Public members** can be accessed by any class including the derived class. **公共成员**可以被任何类访问,包括派生类。

Please check this question 请检查这个问题

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

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