分辨public、protected和private

一、先附上在stackoverflow上看见的一个解答:

class Base {
    public:
        int publicMember;
    protected:
        int protectedMember;
    private:
        int 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”.

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

  • 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.

二、再讲一个故事

class 老王 {
    public:
        罗汉拳;
    protected:
        独孤九剑;
    private:
        九阴真经;
}

class 大王: public 老王 {...}

class 二王: protected 老王 {...}

class 三王: private 老王 {...}

老王有三门武艺。
凡是认识老王的,都知道老王会罗汉拳,并且只要拜师,都可以学到罗汉拳。
只有老王的孩子(和孩子的后代)可能知道老王会独孤九剑,也只有老王的孩子(和孩子的后代)可能学到独孤九剑。
只有老王自己知道九阴真经的存在,也只有他自己和他的朋友(友元)可以学。

老王还有3个孩子。
大王是嫡出,只要认识老王和大王的,都知道大王是老王的孩子。大王知道罗汉拳和独孤九剑的存在,并且可以把罗汉拳传给外人。
二王是庶出,只有二王和二王的后代们知道自己是老王的后代。二王知道罗汉拳和独孤九剑的存在,但不能将罗汉拳外传。
三王是私生子,只有三王知道自己是老王的后代,三王都不敢告诉自己的后代。三王不知道老王会武功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值