访问方法指针到受保护的方法? [英] Access to method pointer to protected method?

查看:112
本文介绍了访问方法指针到受保护的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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

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

会出现此错误:

t.cpp: In member function 'void D::Bar()':
Line 3: error: 'void B::Foo()' is protected




  • 为什么我可以调用受保护的方法,它的地址?

  • 有没有办法标记从派生类完全访问的东西,而不是只能从派生类 li>

    • Why can I call a protected method but not take its address?
    • Is there a way to mark something fully accessible from derived classes rather than only accessible from derived classes and in relation to said derived class?
    • BTW:这看起来相关,但是我正在寻找一个引用,在规范等中调用(并且希望这将导致如何使事情按照我期望的方式工作)。

      BTW: This looks related but what I'm looking for a reference to where this is called out in the spec or the like (and hopefully that will lead to how to get things to work the way I was expecting).

      推荐答案

      您可以通过写& D :: Foo 而不是<$ c,通过 D $ c>& B :: Foo 。

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

      查看此编译内容: http://www.ideone.com/22bM4

      但这不会编译(您的代码): http:/ /www.ideone.com/OpxUy

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

      为什么我可以调用受保护的方法,

      您不能通过写& B :: Foo Foo 是受保护的成员,您不能从 B 外部访问,地址。但是写& D :: Foo 可以,因为 Foo 成为 D

      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.

      & amp; ; B :: Foo 具有与 b.Foo() pB-> Foo()在以下代码中:

      &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!
        }
      

      请参阅ideone上的错误:http://www.ideone.com/P26JT

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

      这篇关于访问方法指针到受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆