如何从同一个类的静态函数访问一个类的私有成员? [英] C++ - How to access private members of a class, from a static function of the same class?

查看:82
本文介绍了如何从同一个类的静态函数访问一个类的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所拥有的:

所以我有一个带有私有成员的类和一个静态函数.该功能必须确实是静态的,我无法更改.

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.

我想要的东西:

我需要从静态功能访问私有成员.有任何想法吗?:)

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

请检查以下代码:

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'
}

推荐答案

静态成员函数是 class 的一部分,并且没有与之关联的对象实例(换句话说,没有静态成员函数中的指针).为了能够访问非静态成员变量,您需要一个类的实际实例.

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.

使用旧的C库设置回调时,常见的解决方案是使用某种用户数据指针,并将其分配给该类的实例.对您来说幸运的是,GLFW库您可以使用这样的指针

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.

这篇关于如何从同一个类的静态函数访问一个类的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆