zealotds 发表于 2013-2-5 00:57:05

C++ Access Control Modifiers / C++ 访问控制符

I saw many debates on the web about the access control modifier. And I also have some confusion although I have never used other derive method than "public". And I believe only the compiler will tell you the truth:
见到网上有很多关于C++访问控制符的问题,自己也有些迷糊。虽然自己在实际工程中从来没有用过除public以外的继承。再多的讨论都不如让编译器来告诉你事实来的实在:

// NOTICE: the lines commented out below can get compiled!class B {    public:      void public_foo() {            cout << "public_foo" << endl;      }    protected:      void protected_foo() {            cout << "protected_foo" << endl;      }    private:      void private_foo() {            cout << "private_foo" << endl;      }};class D1 : public B {    public:      void test () {            B::public_foo();            B::protected_foo();            // B::private_foo();      }};class D2 : protected B {    public:      void test () {            B::public_foo();            B::protected_foo();            // B::private_foo();      }};class D3 : private B {    public:      void test () {            B::public_foo();            B::protected_foo();            // B::private_foo();      }};class DD1 : public D1 {    public:      void test_inherits () {            B::public_foo();            B::protected_foo();            // B::private_foo();      }};class DD2 : public D2 {    public:      void test_inherits () {            B::public_foo();            B::protected_foo();            // B::private_foo();      }};class DD3 : public D3 {    public:      void test_inherits () {            // B::public_foo();            // B::protected_foo();            // B::private_foo();      }};int main(int argc, const char *argv[]){    DD1 dd1;    dd1.public_foo();    // you can't change the originally protected to public    // with public inheritance    // dd1.protected_foo();    // nor the private ones    // dd1.private_foo();    DD2 dd2;    // but you can change a public to protected    // dd2.public_foo();    DD3 dd3;    // DD3 has everthing tagged with private    // you have nothing to do with it      return 0;}
So:


[*]the public/protected/private modifier for field or method declaration controls the member's access in its derived class.
[*]the public/protected/private modifier for inheriting modifies the access defined by the above rule to the modifier you used here.
[*]the modification made by the above rule only happens if the it makes the member less accessible

结论:


[*]public/protected/private被用在字段或方法的声明时控制的是该成员在其子类中的访问权
[*]public/protected/private被用于继承关系时可以修改上述声明的访问权为你在此指定的修饰符
[*]上述修改只在当这种修改使得成员访问权“更小”时才会发生
页: [1]
查看完整版本: C++ Access Control Modifiers / C++ 访问控制符