4
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 =&Derived :: foo;'很好地顺便说一句。 – dyp
我想禁止这个的原因与禁止访问另一个“Base”类型对象的'foo'相同;即'Base b; b.foo = 42;'在Derived :: bar'中也是禁止的。 – dyp