派生类中受保护的成员函数地址不可访问 [英] Protected member function address in derived class is not accessible

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

问题描述

#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]

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

An additional access check beyond those described earlier in Clause 11 is applied when a non-static data member or non-static member function is a protected member of its naming class (11.2) As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C. If the access is to form a pointer to member (5.3.1), the nested-name-specifier shall denote C or a class derived from C. All other accesses involve a (possibly implicit) object expression (5.2.5). In this case, the class of the object expression shall be C or a class derived from C. [Example:

 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.

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

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