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

时光总嘲笑我的痴心妄想 提交于 2019-12-05 10:07:19

问题


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 main application. Each of these have some static member functions which operate on the data in the nase class. (They need to be static as are used as function pointers elsewhere). In its simplest form my issue is shown below.

class Base {
protected:
  int var ;
};

class Derived : public Base {
  static bool Process( Base *pBase ) {
    pBase->var = 2;
    return true;
  }
};

My compiler complains that I cannot access protected members of pBase even though Derived has protected access to Base. Is there any way around this or am I misunderstanding something? I can make the Base variables public but this would be bad as in my real instance these are a lump of allocated memory and the semaphores to protect it for multithreading.

Help?


回答1:


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...
    }
} ;



回答2:


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<Derived*>(pBase))->var = 2;


来源:https://stackoverflow.com/questions/7307200/can-i-access-a-base-classes-protected-members-from-a-static-function-in-a-derive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!