C++ - How to access private members of a class, from a static function of the same class?

时光总嘲笑我的痴心妄想 提交于 2020-12-26 05:01:42

问题


What I have:

So I have a class with a private member, and a static function. The function must really be static and I can't change that.

What I want:

I need to access, from the static function, the private member. Any ideas? :)

Please check the code bellow:

class Base
{
private:
   int m_member;
public:
   Base() : m_member(0) {};
   ~Base() {};

   static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); /* This must really be static because it is coming from C */
};

void Base::key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    m_member = 1; // <---- illegal reference to non-static member 'Base::m_member'
}

回答1:


Static member functions are part of the class, and have no object instance associated with them (in other words, there's no this pointer in static member functions). To be able to access non-static member variables you need an actual instance of the class.

A common solution when setting callbacks using old C libraries, is to use some kind of user-data pointer, and assign it to an instance of the class. Fortunately for you, the GLFW library have such a pointer that you can use.




回答2:


A static member function cannot access a non-static member (unless it creates its own local instance the non-static member would belong to).

This is because non-static members belong to an instance of the class, and the static member does not. Think about it: If you wrote

Base::callback(...);

what m_member should this access? There simply is no instance of Base and thus not m_member.




回答3:


You can't. You need an instance to get to the non-static private. In the static method you don't have an instance available.

So you need some way to get an instance, either by passing it to the static method, or by being able to get it from somewhere else. But in that case, you could as well make it a non-static method.




回答4:


You could make m_member

static int m_member;


来源:https://stackoverflow.com/questions/31367959/c-how-to-access-private-members-of-a-class-from-a-static-function-of-the-sa

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