六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 81|回复: 0

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

[复制链接]

升级  92%

52

主题

52

主题

52

主题

秀才

Rank: 2

积分
188
 楼主| 发表于 2013-2-5 00:57:05 | 显示全部楼层 |阅读模式
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被用于继承关系时可以修改上述声明的访问权为你在此指定的修饰符
  • 上述修改只在当这种修改使得成员访问权“更小”时才会发生
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表