通过成员指针访问受保护的成员:这是黑客吗? [英] Access to protected member through member-pointer: is it a hack?
问题描述
我们都知道只能从派生类自己的实例访问从基类中指定的protected
成员.这是标准中的一项功能,并且已经在Stack Overflow上进行了多次讨论:
We all know members specified protected
from a base class can only be accessed from a derived class own instance. This is a feature from the Standard, and this has been discussed on Stack Overflow multiple times:
-
无法从派生类型的作用域访问另一个实例的受保护成员 ; -
为什么我的对象无法访问在公共基类中定义的另一个对象的受保护成员? - 还有其他人.
- 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?
- And others.
但是似乎有可能绕过成员指针的限制,因为用户chtz
But it seems possible to walk around this restriction with member pointers, as user 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;
}
};
为什么会这样,这是实现标准中的通俗易懂的功能还是出现故障?
Why is this possible, is it a wanted feature or a glitch somewhere in the implementation or the wording of the Standard?
从评论中出现了另一个问题:如果用实际的Base
调用Derived::f
,这是不确定的行为吗?
From comments emerged another question: if Derived::f
is called with an actual Base
, is it undefined behaviour?
推荐答案
使用 class成员访问权限无法访问成员的事实 [class.access] 不会使该成员无法使用其他表达式访问.
The fact that a member is not accessible using class member access expr.ref (aclass.amember
) due to access control [class.access] does not make this member inaccessible using other expressions.
表达式&Derived::value
(其类型为int Base::*
)完全符合标准,它指定Base
的成员value
.然后,表达式a_base.*p
(其中p
是指向Base
的成员的指针,而a_base
是Base
的实例的指针)也是
The expression &Derived::value
(whose type is int Base::*
) is perfectly standard compliant, and it designates the member value
of Base
. Then the expression a_base.*p
where p
is a pointer to a member of Base
and a_base
an instance of Base
is also standard compliant.
因此,任何符合标准的编译器都应使表达式other.*(&Derived::value);
定义为行为:访问other
的成员value
.
So any standard compliant compiler shall make the expression other.*(&Derived::value);
defined behavior: access the member value
of other
.
这篇关于通过成员指针访问受保护的成员:这是黑客吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!