在对问题“为什么我的对象无法访问在公共基类中定义的另一个对象的受保护成员?”的此答案中,可以看到以下内容:
鉴于我遇到的这两个错误,我开始想:为什么我可以从“Derived”的范围内访问另一个“Derived”实例的受保护成员,但无论“Derived”是否从“Base”派生,都无法在相同的范围内访问另一个“Base”实例的受保护成员?简而言之:在这种情况下,“protected”比“private”更“私有”的原因是什么?
注: 请不要将此问题视为链接问题; 欢迎提出更好的标题建议。
我可能没有理解正确,或者以下最小工作示例(在线演示)证明其错误。只能从自己的基类实例中访问受保护的成员。
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”实例的受保护成员,但无论“Derived”是否从“Base”派生,都无法在相同的范围内访问另一个“Base”实例的受保护成员?简而言之:在这种情况下,“protected”比“private”更“私有”的原因是什么?
注: 请不要将此问题视为链接问题; 欢迎提出更好的标题建议。
Base
引用,就这样。 - StoryTeller - Unslander Monica