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
答案 0 :(得分: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();
}
如果Base的成员的范围是私有的,那么您将获得预期的访问错误。