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;
顺便说一句,运行正常。 - dypfoo
的访问相同;即在Derived::bar
中也禁止使用Base b; b.foo = 42;
。 - dypint *i = &foo; *i = 7;
。或者,你知道的,foo = 7;
。 - chris