我们都知道从一个基类指定为 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;
}
};
为什么这是可能的?这是一个想要的功能还是实现中存在的某个故障或标准措辞问题?
从评论中出现了另一个问题:如果用实际的 Base
调用 Derived::f
,会产生未定义行为吗?
f
可以是静态的,这有助于避免实际上创建Derived
对象。 - 463035818_is_not_a_number