【问题标题】:Derived class cannot use member pointer to protected base class member派生类不能使用成员指针指向受保护的基类成员
【发布时间】:2014-09-12 05:15:45
【问题描述】:
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();
}

我不明白为什么我的派生类型不能指向基类的受保护成员。它有权访问该成员。它可以调用类似范围的函数。为什么它不能做一个成员指针?我正在使用 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

【问题讨论】:

  • 顺便说一句,如果我添加一个朋友声明这工作得很好,但是当我只是试图访问一个我应该有权访问的受保护成员时,将我的派生类声明为朋友似乎很奇怪已经到了。
  • int Base::* i = &amp;Derived::foo; 工作正常。
  • 我想禁止这个的原因和禁止访问另一个Base类型的对象foo是一样的;即Base b; b.foo = 42; 也被禁止在Derived::bar 内。
  • 或者只是int *i = &amp;foo; *i = 7;。或者,你知道,foo = 7;
  • @chris,我特意在寻找使用成员指针的解决方案。显然,对于此示例代码,它们不是必需的,但这只是示例代码。在我的实际代码中,我需要一个成员指针。

标签: c++ member-pointers


【解决方案1】:

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

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();
}

如果 Base 的成员被限定为私有,那么您会收到预期的缺少访问错误。

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2018-03-24
    • 1970-01-01
    • 2016-02-23
    相关资源
    最近更新 更多