c++ - 如何从派生类访问基类中的 protected 方法?

标签 c++ protected derived-class

下面是一段令我恼火的代码示例:

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' */
    }
};

如何访问 protected 重写函数?

感谢您的帮助。 :o)

最佳答案

基类中的 protected 成员只能由当前对象访问。
因此,您可以调用 this->foo(),但不允许调用 this->b->foo()。这与 Derived 是否为 foo 提供实现无关。

此限制背后的原因是,否则很容易绕过 protected 访问。您只需创建一个像 Derived 这样的类,突然间您就可以访问其他类(例如 OtherDerived)的部分,这些部分本应不被外部人员访问。

关于c++ - 如何从派生类访问基类中的 protected 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4672438/

相关文章:

c++ - 如何在没有友元函数的情况下重载 << 运算符

C++简单类

c++ - Qt 的 MinGW、Code::Blocks 的 MinGW 和 MinGW 本身有什么区别吗?

c++ - 如何跳过一行标准输入?

java - 静态类是否只包含java中的静态方法?

java - 谁能解释一下这里发生了什么 : "protected" modifier in java

ruby-on-rails - 你曾经在 Rails 中使用 protected 可见性吗?

C++在派生类中初始化基类的const int?

c# - XMLSerializer 为什么要取基类的 DefaultValue 属性来序列化

c++ - 如何在可变参数模板中声明 "implicit conversion"?