派生类不能使用成员指针来保护基类成员

Dan*_*bek 4 c++ member-pointers

include <stdio.h>

class Base
{
protected:
    int foo;
    int get_foo() { return foo; }
};

class Derived : public Base
{
public:
    void bar()
    {
        int Base::* i = &Base::foo;
        this->*i = 7;
        printf("foo is %d\n", get_foo());
    }
};


int main()
{
    Derived d;
    d.bar();
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我的派生类型不能指向基类的受保护成员.它有权访问该成员.它可以调用类似范围的函数.为什么它不能成为成员指针?我正在使用gcc 4.1.2,我收到此错误:

test.cc: In member function ‘void Derived::bar()’:
test.cc:6: error: ‘int Base::foo’ is protected
test.cc:15: error: within this context
Run Code Online (Sandbox Code Playgroud)

Dan*_*bek 5

通过反复试验,我找到了一个有意义的解决方案.即使它是您指向的基类继承成员,指针仍应是Derived类的成员指针.因此,以下代码有效:

include <stdio.h>

class Base
{
protected:
    int foo;
    int get_foo() { return foo; }
};

class Derived : public Base
{
public:
    void bar()
    {
        int Derived::* i = &Derived::foo;
        this->*i = 7;
        printf("foo is %d\n", get_foo());
    }
};

int main()
{
    Derived d;
    d.bar();
}
Run Code Online (Sandbox Code Playgroud)

如果Base的成员的范围是私有的,那么您将获得预期的访问错误.