在Flex(以及许多其他语言)中,类的函数/方法可以声明为私有或受保护(或公共).有什么不同?我的印象是它与子类的关系以及事物如何被继承或可以被调用有关,但我不确定究竟是什么.
一般来说:
私人成员只能由班级本身访问.
受保护的成员只能由类本身及其后代访问.
每个人都可以访问公共成员.
因此,当您从私人到受保护到公共时,可见性会增加.
在C++中,你可以控制会员的知名度应该与前面加上基类名被继承到后代private
,protected
或public
关键字,这意味着你想要的基类成员的知名度,至多在这一水平.
class A { private: int privA; protected: int protA; public: int pubA; // privA can be accessed inside class A // protA can be accessed inside class A // pubA can be accessed inside class A }; // pubA can be accessed by anyone class B : public A { // No change to visibility of members // privA can't be accessed inside class B // protA can be accessed inside class B // pubA can be accessed inside class B }; // pubA can be accessed by anyone class C : protected A { // Public members downgraded to protected // privA can't be accessed inside class C // protA can be accessed inside class C // pubA can be accessed inside class C }; // None of the members can be accessed outside class C class D : private A { // Public and protected members downgraded to private // privA can't be accessed inside class D // protA can't be accessed inside class D // pubA can't be accessed inside class D }; // None of the members can be accessed outside class D
在上述每个案例中,后代课程当然能够介绍他们自己的私人,受保护和公共成员.