我们都知道protected
从基类指定的成员只能从派生类自己的实例中访问。这是标准中的一个特性,这已经在 Stack Overflow 上多次讨论过:
但似乎可以用成员指针绕过这个限制,正如用户 chtz向我展示的那样:
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;
}
};
为什么这是可能的,它是一个想要的特性还是实现或标准的措辞中的某个小故障?
从评论中出现了另一个问题:如果Derived::f
用实际调用Base
,它是未定义的行为吗?