正文

对受保护成员的一个额外访问控制2008-05-13 11:42:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/aurora/34999.html

分享到:

对于受保护的成员变量,子类对其的访问有一个额外的限制:

Clause 11.5:

When a friend or a member function of a derived class references a protected nonstatic member function or protected nonstatic data member of a base class, an access check applies in addition to those described earlier in clause 11.102) Except when forming a pointer to member (5.3.1), the access must be through a pointer to, reference to, or object of the derived class itself (or any class derived from that class) (5.2.5). If the access is to form a pointer to member, the nested-name-specifier shall name the derived class (or any class derived from that class).

例子:

class Base{

protected:

     Base(int){}

     int i;

};

class Derive:public Base{

public:

     Derive():Base(100){              //OK

          Base b(100);                //ill-formed: Cannot access protected member

          int Base::* p = &Base::i;   //ill-formed: Cannot access protected member

          int Base::*pd = &Derive::i; //OK:If the access is to form a pointer to

          //member, the nested-name-specifier shall name the derived class

          // (or any class derived from that class)

     }

     void foo( Derive *pd, Base *pb ){

          int temp1  = pb->i; //ill-formed: cannot access protected member

          int temp2  = pd->i; //OK:   access through pointer to derived class

          int temp3  = i;     //OK:   access through 'this'  

    }

};

阅读(2852) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册