Access to method pointer to protected method?

前端 未结 6 627
情歌与酒
情歌与酒 2020-12-03 17:27

This code:

class B {
 protected:
  void Foo(){}
}

class D : public B {
 public:
  void Baz() {
    Foo();
  }
  void Bar() {
    printf(\"%x\\n\", &B::F         


        
6条回答
  •  一整个雨季
    2020-12-03 18:17

    You can take the address through D by writing &D::Foo, instead of &B::Foo.

    See this compiles fine : http://www.ideone.com/22bM4

    But this doesn't compile (your code) : http://www.ideone.com/OpxUy


    Why can I call a protected method but not take its address?

    You cannot take its address by writing &B::Foo because Foo is a protected member, you cannot access it from outside B, not even its address. But writing &D::Foo, you can, because Foo becomes a member of D through inheritance, and you can get its address, no matter whether its private, protected or public.

    &B::Foo has same restriction as b.Foo() and pB->Foo() has, in the following code:

    void Bar() {
        B b;
        b.Foo();     //error - cannot access protected member!
        B *pB = this;
        pB->Foo();   //error - cannot access protected member!
      }
    

    See error at ideone : http://www.ideone.com/P26JT

提交回复
热议问题