私有、公共和受保护继承之间的区别 [英] Difference between private, public, and protected inheritance

查看:40
本文介绍了私有、公共和受保护继承之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ 中的publicprivateprotected 继承有什么区别?

What is the difference between public, private, and protected inheritance in C++?

我在 SO 上发现的所有问题都涉及特定案例.

All of the questions I've found on SO deal with specific cases.

推荐答案

为了回答这个问题,我想先用我自己的话来描述成员的访问器.如果您已经知道这一点,请跳到标题下一个:".

To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".

我知道有三种访问器:publicprotectedprivate.

There are three accessors that I'm aware of: public, protected and private.

让:

class Base {
    public:
        int publicMember;
    protected:
        int protectedMember;
    private:
        int privateMember;
};

  • 所有知道 Base 的东西也知道 Base 包含 publicMember.
  • 只有孩子(和他们的孩子)知道 Base 包含 protectedMember.
  • 除了Base 没有人知道privateMember.
    • Everything that is aware of Base is also aware that Base contains publicMember.
    • Only the children (and their children) are aware that Base contains protectedMember.
    • No one but Base is aware of privateMember.
    • 知道"的意思是承认存在,从而能够访问".

      By "is aware of", I mean "acknowledge the existence of, and thus be able to access".

      公共、私有和受保护的继承也是如此.让我们考虑一个类 Base 和一个继承自 Base 的类 Child.

      The same happens with public, private and protected inheritance. Let's consider a class Base and a class Child that inherits from Base.

      • 如果继承是public,所有知道BaseChild的东西也知道Child继承自 Base.
      • 如果继承是 protected,则只有 Child 及其子代知道它们从 Base 继承.
      • 如果继承是private,那么除了Child 之外没有人知道继承.
      • If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base.
      • If the inheritance is protected, only Child, and its children, are aware that they inherit from Base.
      • If the inheritance is private, no one other than Child is aware of the inheritance.

      这篇关于私有、公共和受保护继承之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆