本文介绍了派生类中受保护的成员函数地址不可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Here I am trying to get address of protected member function of base class. I am getting this error.

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

将foo更改为公共作品.也可以打印&B::foo.您能解释一下为什么我们无法获得基类的受保护成员函数的地址吗?

Changing foo to public works. Also printing &B::foo works. Can you please explain why we can't get address of protected member function of base class?

推荐答案

B访问A的受保护成员.在您的示例中,您尝试通过A访问foo,在这种情况下,B是否从A派生无关紧要.

B is allowed to access protected members of A as long as the access is performed through an object of type B. In your example you're trying to access foo through A, and in that context it is irrelevant whether B derives from A or not.

从N3337开始,§11.4/1 [受保护的类]

From N3337, §11.4/1 [class.protected]

 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
   // ...
 }
 // ...

-结束示例]

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

Your example is very similar to the code in D2::mem, which shows that trying to form a pointer to a protected member through B instead of D2 is ill-formed.

这篇关于派生类中受保护的成员函数地址不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 14:50