无法访问派生类中受保护的成员函数地址

Ash*_*hot 9 c++ inheritance member-function-pointers protected

#include <iostream>

class A {
protected:
    void foo()
    {}
};

class B : public A {
public:
    void bar()
    {
       std::cout << (&A::foo) << std::endl;
    }
};

int main()
{
    B b;
    b.bar();
}
Run Code Online (Sandbox Code Playgroud)

这里我试图获取基类的受保护成员函数的地址.我收到了这个错误.

main.cpp: In member function ‘void B::bar()’:
main.cpp:5: error: ‘void A::foo()’ is protected
main.cpp:13: error: within this context
make: *** [all] Error 1
Run Code Online (Sandbox Code Playgroud)

将foo改为公共工程.还有印刷&B::foo作品.能否解释为什么我们无法获得基类的受保护成员函数的地址?

Pra*_*ian 6

BA只要通过类型对象执行访问,就允许访问受保护的成员B.在您的例子中,你正在试图访问fooA,在这方面它是无关紧要是否B派生自A与否.

来自N3337,§11.4/ 1 [class.protected]

当非静态数据成员或非静态成员函数是其命名类的受保护成员时,将应用超出第11章中所述之外的其他访问检查(11.2)如前所述,授予对受保护成员的访问权限,因为引用发生在朋友或某个类的成员中C.如果访问要形成指向成员的指针(5.3.1),则嵌套名称说明符应表示C或派生自的类C.所有其他访问都涉及(可能是隐式的)对象表达式(5.2.5).在这种情况下,对象表达式C的类应该是派生自的类C.[ 例如:

 class B {
 protected:
   int i;
   static int j;
 };
 class D1 : public B {
 };
 class D2 : public B {
   friend void fr(B*,D1*,D2*);
   void mem(B*,D1*);
 };
 // ...
 void D2::mem(B* pb, D1* p1) {
   // ...
   int B::* pmi_B = &B::i; // ill-formed
   int B::* pmi_B2 = &D2::i; // OK
   // ...
 }
 // ...
Run Code Online (Sandbox Code Playgroud)

- 末端的例子 ]

您的示例与代码非常相似D2::mem,它表明尝试通过B而不是形成一个指向受保护成员的指针D2.