Can I access a base classes protected members from a static function in a derived class?

前端 未结 2 1685
我在风中等你
我在风中等你 2021-02-18 16:28

I have a program where I need to make a base class which is shared between a dll and some application code. Then I have two different derived classes, one in the dll one in the

2条回答
  •  眼角桃花
    2021-02-18 17:13

    Access specifier applies to the Derived class handle (reference/pointer/object) and not the methods of Derived class itself. Even if the method was not static, you would have ended up with the same error. Because you are not accessing var with the derived handle. Demo.

    The correct way is to provide a setter method:

    class Base {
    protected:
      int var ;
    public:
      void setVar(const int v) { var = v; } // <--- add this method
    };
    

    Note: There is one more way out, but I am not sure if it's elegant.

    (static_cast(pBase))->var = 2;
    

提交回复
热议问题