c++ - 如何从派生类通过基类 ptr 访问 protected 基类函数

标签 c++ protected derived-class

我有一个抽象类 A,我从它继承了许多类。在派生类中,我试图通过 A 指针访问 A 中的 protected 函数。但是我得到一个编译器错误。

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 中声明的 protected 成员 A::f。

如果我将 mAPtr 声明为 D*,而不是 A*,则一切都会编译。我不明白为什么会这样。

最佳答案

依靠 private 访问对相同类型的不相关实例起作用。

依赖于protected 访问适用于相同类型(以及更多派生类型)的不相关实例。

但是,依赖于protected 访问对基类型的不相关实例起作用。

[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 派生的东西,但不是 A

这是一个经常被质疑的关于 C++ 的可爱怪癖,但它的设计是为了尽量避免陷阱。毕竟,您不知道 *mAPtr 真正 有什么类型。

关于c++ - 如何从派生类通过基类 ptr 访问 protected 基类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7711237/

相关文章:

C++ 嵌套类 : Instantiate Child Class From Main

C#项目没有为自己写的c++ dll定义入口点

c++ - 将 char 转换为 int 时 vector 下标超出范围

php - 如何在PHP中获取对象的 protected 属性

Scala: "override protected val"在定义案例类构造函数时导致错误

objective-c - 在 Objective-C 中完成 protected 属性的解决方法

c++ - *.so 使用来自其他 *.so 的函数时如何使用 dlopen 和 dlsym

派生参数化构造函数的 C++ 设置值

python - 如何在 Python C-API 中动态创建派生类型

c++ - 基于组件的架构 C++