2014-07-21 117 views
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 
+0

顺便说一句,如果我添加一个朋友声明,这工作得很好,但对于我只是试图访问一个我应该有权访问的受保护成员而言,将我的派生类声明为朋友似乎很奇怪。 –

+1

'int Base :: * i =&Derived :: foo;'很好地顺便说一句。 – dyp

+0

我想禁止这个的原因与禁止访问另一个“Base”类型对象的'foo'相同;即'Base b; b.foo = 42;'在Derived :: bar'中也是禁止的。 – dyp

回答

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

如果基地成员和作用域为私有,那么你得到的预期缺乏访问错误的。

相关问题