如何从派生类访问基类中的protected方法? [英] How to access protected method in base class from derived class?

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

问题描述

这里是一个让我厌烦的代码示例:

Here is a sample of code that annoys me:

class Base {
  protected:
    virtual void foo() = 0;
};

class Derived : public Base {
  private:
    Base *b; /* Initialized by constructor, not shown here
                Intended to store a pointer on an instance of any derived class of Base */

  protected:
    virtual void foo() { /* Some implementation */ };
    virtual void foo2() {
      this->b->foo(); /* Compilator sets an error: 'virtual void Base::foo() is protected' */
    }
};

如何访问受保护的覆盖函数?

How do you access to the protected overrided function?

感谢您的帮助。 :o)

Thanks for your help. :o)

推荐答案

基类中的受保护成员只能由当前对象访问。

因此,您可以调用 this-> foo(),但不允许调用 this-> b-> foo ()。这与 Derived 是否为 foo 提供了一个实现无关。

Protected members in a base-class are only accessible by the current object.
Thus, you are allowed to call this->foo(), but you are not allowed to call this->b->foo(). This is independent of whether Derived provides an implementation for foo or not.

这个限制背后的原因是,否则将很容易绕过受保护的访问。您只需创建一个类 Derived ,然后突然你也可以访问其他类的部分(如 OtherDerived )应该是外人无法进入的。

The reason behind this restriction is that it would otherwise be very easy to circumvent protected access. You just create a class like Derived, and suddenly you also have access to parts of other classes (like OtherDerived) that were supposed to be inaccessible to outsiders.

这篇关于如何从派生类访问基类中的protected方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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