分辨public、protected和private

来源:互联网 发布:avi播放器 for mac 编辑:程序博客网 时间:2024/03/29 19:23

一、先附上在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
原创粉丝点击