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

后端 未结 4 806
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 05:11

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.

相关标签:
4条回答
  • 2021-01-17 05:19

    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.

    0 讨论(0)
  • 2021-01-17 05:20

    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.

    0 讨论(0)
  • 2021-01-17 05:40

    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.

    0 讨论(0)
  • 2021-01-17 05:42

    You could make m_member

    static int m_member;
    
    0 讨论(0)
提交回复
热议问题