通过指向派生类中基类的指针来调用基类中的受保护方法 [英] Calling protected method in base class via pointer to base class in derived class

查看:95
本文介绍了通过指向派生类中基类的指针来调用基类中的受保护方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想理解为什么当我从基类的指针通过派生类调用从基类声明并实现的受保护方法时,得到编译错误(C2248),以及当我通过派生类的指针从派生类调用它时得到编译错误实例,编译通过.

I would like to understand why when I call protected method, declared and implemented in base class, from derived class via pointer to base class I get compilation error (C2248) and when I call it from derived class via pointer to derived class instance, compilation pass.

我了解这是语言的一部分,但我想了解原因

I understand it is part of the language but I want to understand why

我的解释是,当我通过派生类中的指向基类的指针调用基类的受保护成员时,编译失败,因为基类的继承可以是受保护的或私有的,但是当我通过指向派生类的指针在基类中进行调用时,编译失败派生类还可以,因为它是该类的一部分. 是吗?

My explanation is that when I call a protected member of base class via pointer to base class in derived class, compilation fails because the inheritance of base class can be protected or private but when I call it via pointer to derived class in a derived class it o.k because it is part of the class. Is that right?

例如

class Base 

{

protected:

   virtual void func() {}

}

class Derived : public Base

{

public:

   virtual void myMethod()

   {

      Base* pBase = new Base;

      pBase->func();          -> compilation error (C2248)

      Derived* pDerived = new Derived;

      pDerived->func();       -> O.K

    }
}

推荐答案

失败行是不可编译的,因为您正在访问Base的实例-只有公共方法可以通过这种方式访问​​.如果您在myMethod()中这样做:

The failing line is not compilable because you are accessing an instance of Base - only public methods can be accessed this way. If you do this in myMethod():

Base::func();

它应该编译,因为现在我们正在访问this的继承方法. pDerived::myMethod()调用Derived构造函数有点奇怪吗?

it should compile because now we are accessing the inherited method for this. Kind of weird to have pDerived::myMethod() call the Derived constructor?

这篇关于通过指向派生类中基类的指针来调用基类中的受保护方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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