我们都知道从基类中指定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;
}
};
为什么会出现这种情况,它是一个想要的特性还是在实现或标准的措辞中的某个地方出现的故障?
评论中出现了另一个问题:if Derived::f
is called with an actual Base
,是未定义的行为吗?
最佳答案
使用类成员访问权限无法访问成员这一事实 expr.ref (aclass.amember
) 由于访问控制 [class.access]不会使该成员无法使用其他表达式访问。
表达式&Derived::value
(whose type is int Base::*
)完全符合标准,它指定了 Base
的成员 value
。然后表达式 a_base.*p
其中 p
是指向 Base
成员的指针,而 a_base
是Base
也是 standard compliant .
因此任何符合标准的编译器都应使表达式 other.*(&Derived::value);
定义行为:访问 other的成员
.value
关于c++ - 通过成员指针 : is it a hack? 访问 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49550663/