【发布时间】:2023-08-24 06:25:01
【问题描述】:
在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 不同的事实?铊;博士:在这种情况下,是什么让protected 比private 更“私密”?
注意事项:
- 请不要将此问题作为链接问题的副本关闭;
- 欢迎提供更好的标题建议。
【问题讨论】:
-
访问说明符的工作方式相同,即使您在范围内看到对象。您使用
Base引用,这就是她所写的全部内容。
标签: c++ language-lawyer encapsulation protected