在Flex(以及许多其他语言)中,类的函数/方法可以声明为私有或受保护(或公共)。有什么不同?我的印象是它与子类的关系以及事物如何被继承或可以被调用有关,但我不确定究竟是什么。
答案 0 :(得分:11)
一般来说:
因此,当您从私人到受保护再到公共时,可见性会增加。
在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
在上述每个案例中,后代课程当然都能介绍他们自己的私人,受保护和公共成员。