c++ - 通过成员指针 : is it a hack? 访问 protected 成员

标签 c++ language-lawyer protected access-specifier member-pointers

我们都知道从基类中指定protected的成员只能从派生类自己的实例中访问。这是标准中的一项功能,在 Stack Overflow 上已多次讨论过:

但似乎可以用成员指针绕过这个限制,因为用户 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;
    }
};

Live demo on coliru

为什么会出现这种情况,它是一个想要的特性还是在实现或标准的措辞中的某个地方出现的故障?


评论中出现了另一个问题: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_baseBase 也是 standard compliant .

因此任何符合标准的编译器都应使表达式 other.*(&Derived::value); 定义行为:访问 othervalue.

关于c++ - 通过成员指针 : is it a hack? 访问 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49550663/

相关文章:

c++ - 尝试使用比较运算符对对象 vector 进行排序

c++ - 从 C++ 队列中间删除一个节点

Java : private method vs final class

php - __construct 的可见性

c++ - 为什么 protected 继承会导致 dynamic_cast 失败?

C++ 段错误 : 11, 试图重载运算符 <<

c++ - OpenCV 视频捕获未加载文件

c++ - C 或 C++ 是否保证 array < array + SIZE?

c++ - 为什么结构和类定义可以在多个翻译单元上重复?

c++ - 构造函数在 g++ 和 clang++ 中委托(delegate)给自己