对于受保护的成员变量,子类对其的访问有一个额外的限制:
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'
}
};
评论