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

前端 未结 2 1671
我在风中等你
我在风中等你 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:02

    In general (regardless of whether the function is static or not), a member function of the derived class can only access protected base class members of objects of its type. It cannot access protected members of the base if the static type is not that of the derived class (or a class derived from it). So:

    class Base {
    protected:
        int var;
     } ;
    
    class Derived : public Base {
        static void f1( Derived* pDerived )
        {
            pDerived->var = 2; // legal, access through Derived...
        }
        static bool Process( Base *pBase )
        {
            pBase->var = 2 ;  // illegal, access not through Derived...
        }
    } ;
    

提交回复
热议问题