【发布时间】:2018-09-08 02:13:09
【问题描述】:
我们都知道从基类中指定protected 的成员只能从派生类自己的实例中访问。这是标准中的一项功能,在 Stack Overflow 上已多次讨论过:
- Cannot access protected member of another instance from derived type's scope ;
- Why can't my object access protected members of another object defined in common base class?
- 等等。
但似乎可以用成员指针绕过这个限制,就像用户 chtz has shown me:
struct Base { protected: int value; };
struct Derived : Base
{
void f(Base const& other)
{
//int n = other.value; // error: 'int Base::value' is protected within this context
int n = other.*(&Derived::value); // ok??? why?
(void) n;
}
};
为什么会出现这种情况,它是一个想要的功能还是在实施或标准的措辞中的某个地方出现的故障?
来自 cmets 的另一个问题是:if Derived::f is called with an actual Base,它是未定义的行为吗?
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
@YvetteColomb 这是寻找问题解决方案/改进问题的集体努力。有没有办法把它们放回去?其中仍有一些信息可以改善接受的答案。
-
他们都还在链接的聊天中。
-
这拯救了我的一天。请注意the method
fcan be static,这有助于避免实际创建Derived对象
标签: c++ language-lawyer protected access-specifier member-pointers