[英]C++ - How to access private members of a class, from a static function of the same class?
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'
}
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). 静态成员函数是该类的一部分,并且没有与之关联的对象实例(换句话说,静态成员函数中没有
this
指针)。 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. 使用旧的C库设置回调时,一种常见的解决方案是使用某种用户数据指针,并将其分配给该类的实例。 Fortunately for you, the GLFW library have such a pointer that you can use .
对您来说幸运的是,GLFW库具有您可以使用的指针 。
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.
但是在那种情况下,您也可以使其成为非静态方法。
A static
member function cannot access a non- static
member (unless it creates its own local instance the non- static
member would belong to). static
成员函数不能访问非static
成员(除非它创建该非static
成员所属的本地实例)。
This is because non- static
members belong to an instance of the class
, and the static
member does not. 这是因为非
static
成员属于class
的实例,而static
成员则不属于。 Think about it: If you wrote 考虑一下:如果您写了
Base::callback(...);
what m_member
should this access? 该访问什么
m_member
? There simply is no instance of Base
and thus not m_member
. 根本就没有
Base
实例,因此也没有m_member
。
你可以让m_member
static int m_member;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.