如何访问受保护的基类函数,从派生类通过基类ptr [英] How to access protected base class function, from derived class through base class ptr

查看:115
本文介绍了如何访问受保护的基类函数,从派生类通过基类ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有抽象类A,我从中继承了一些类。在派生类中,我试图访问A槽A指针中的保护函数。但我得到一个编译器错误。

I have abstract class A, from which I inherit a number of classes. In the derived classes I am trying to access protected function in A trough A pointer. But I get a compiler error.

class A
{
   protected:
        virtual  void f()=0;
};

class D : public A
{
    public:
         D(A* aa) :mAPtr(aa){}
         void g();

    protected:
         virtual void f();

    private:
      A* mAPtr; // ptr shows to some derived class instance
};

void D::f(){  }


void D::g()
{
   mAPtr->f();
}

编译器错误说:无法访问在类中声明的受保护成员A :: f A。

The compiler error says : cannot access protected member A::f declared in class A.

如果我声明mAPtr为D *,而不是A *所有的编译。

If I declare mAPtr to be D*, instead A* everything compiles. And I don't understand why is this.

推荐答案

依赖私人访问对同一类型的不相关实例的访问。

Relying on private access works on unrelated instances of the same type.

依赖 protected

但是,依赖 protected 访问 em>工作于基本类型的无关实例。

However, relying on protected access does not work on unrelated instances of a base type.


[n3290:11.5 / 1]: 当派生
类的
朋友或成员函数引用受保护的非静态成员函数或受保护
非静态数据成员一个基类,访问检查适用于前面第11节中描述的那些
。除了形成
a指向成员(5.3.1)的指针,通过指针
到派生类本身(或从该类派生的任何类
(5.2.5)的引用或对象。如果访问是为成员形成指针
,则嵌套名称说明符应命名派生类(或
从该类派生的任何类)。

[n3290: 11.5/1]: When a friend or a member function of a derived class references a protected nonstatic member function or protected nonstatic data member of a base class, an access check applies in addition to those described earlier in clause 11. Except when forming a pointer to member (5.3.1), the access must be through a pointer to, reference to, or object of the derived class itself (or any class derived from that class) (5.2.5). If the access is to form a pointer to member, the nested-name-specifier shall name the derived class (or any class derived from that class).

所以 D 或派生自 D 的东西, code> A 。

So D or something derived from D, but not A.

这是一个可疑的奇怪的C ++,但是设计,以避免陷阱。毕竟,你不知道 * mAPtr 真的类型。

It's an oft-questioned cute oddity about C++ that nonetheless is designed to try to avoid pitfalls. After all, you don't know what type *mAPtr really has.

这篇关于如何访问受保护的基类函数,从派生类通过基类ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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