访问另一个实例的保护成员在this answer问题“?共同基类中定义另一个对象为什么不是我的对象访问保护成员”,一个可以读取:不能从派生类型的范围
您只能从您自己的基类实例访问受保护的成员。
要么我没有正确地得到它或following MCVE (live on coliru)证明她错了:
struct Base { void f(); protected: int prot; };
struct Derived : Base { void g(); private: int priv; };
void Base::f()
{
Base b;
b.prot = prot;
(void) b;
}
void Derived::g()
{
{
Derived d;
(void) d.priv;
}
{
Derived& d = *this;
(void) d.priv;
}
{
Derived d;
(void) d.prot; // <-- access to other instance's protected member
}
{
Derived& d = *this;
(void) d.prot;
}
// ---
{
Base b;
(void) b.prot; // error: 'int Base::prot' is protected within this context
}
{
Base& b = *this;
(void) b.prot; // error: 'int Base::prot' is protected within this context
}
}
在两个错误,我得到想知道的光:我为什么能访问到另一个Derived
实例的保护成员从Derived
的范围,但无法从相同范围访问另一个Base
实例的受保护成员,而不管Derived
是否从Base
开始? TL;博士:在这种情况下,protected
比private
更“私人”吗?
注:
- 请不要关闭这个问题作为链接的问题的重复;
- 更好的标题建议是受欢迎的。
即使您*在范围内查看对象*,访问说明符的作用相同。你使用'Base'引用,这就是她写的全部内容。 – StoryTeller