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发布于 2014-07-21 16:09:32
通过反复试验,我找到了一个有意义的解决方案。即使您所指向的是基类继承的成员,指针仍然应该是派生类的成员指针。因此,以下代码工作:
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的成员范围是私有的,那么您将得到预期的缺少访问错误。
https://stackoverflow.com/questions/24869517
复制相似问题