c++ - C++中通过his指针指示一个对象的方法

标签 c++ visual-studio pointers opengl glfw

<分区>

我目前正在学习 C++ 中的 OpenGL。

我正在尝试通过设置 glfwSetKeyCallback(this->window, ctrl->key_callback); 来读取键盘输入,其中 this->window 是我的 GLFWwindow* windowctrl->key_callback 是我的自定义对象 Controller 的一个方法。

我在使用 MSVC 时遇到编译器错误:

non-standard syntax; use '&' to create a pointer to member

如何通过 Controller* ctrl 指针指示 key_callback 方法?

出现错误的地方:

void Class1::set_callback(Controller* ctrl)
{
    glfwSetKeyCallback(this->window, ctrl->key_callback);
}

Controller .h

#include "Class1.h"
#include "GLFW/glfw3.h"

class Controller
{
    public:
        Controller(Class1* c);
        ~Controller();
        void key_callback(GLFWwindow* glwindow, int key, int scancode, int action, int mods);

    private:
        Window* window;
};

我在 main.cpp 中调用 set_callback

#include "Class1.h"
#include "Controller.h"

int main()
{
    Class1* my_class = new Class1();
    Controller* controller = new Controller(my_class);
    my_class->set_callback(controller);
    return 0;
}

如果我没有正确表述我的问题/标题,请告诉我,我对这种语法很困惑

最佳答案

你不能。非静态成员函数有一个 this 参数。 void key_callback(GLFWwindow* glwindow, int key, int scancode, int action, int mods)的签名其实是void key_callback(Controller*this, GLFWwindow* glwindow, int key, int scancode , int action, int mods).所以根本不满足glfwSetKeyCallback的要求。

我建议您使用 thunk 函数(独立函数或静态成员函数):

void key_callback_thunk(GLFWwindow* glwindow, int key, int scancode, int action, int mods) {
    auto self = static_cast<Controller*>(glfwGetWindowUserPointer(glwindow));
    self->key_callback(glwindow, key, scancode, action, mods);
}

void Class1::set_callback(Controller* ctrl)
{
    glfwSetWindowUserPointer(this->window, ctrl);
    glfwSetKeyCallback(this->window, key_callback_thunk);
}

请注意,glfwSetWindowUserPointer 只能为给定窗口存储一个指针。您再次调用它,该值将被覆盖。

关于c++ - C++中通过his指针指示一个对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53836024/

相关文章:

c++ - 如何在 Qt 中制作可展开/可折叠的部分小部件

c++ - std::string SSO 调整

c# - 更改最小化动画

c++ - 在充满指针的 std::vector 上使用 std::remove_if

c - 在函数内部使用内存分配指针

c - 对指向结构数组的指针执行算术运算时出错

c++ - 如何有效地将 sRGB 转换为 CIELAb,将 CIELab 转换为 sRGB?

c++ AVX512 内部相当于 _mm256_broadcast_ss()?

visual-studio - 可以创建输出类型为 "none"的 Visual Studio 项目吗?

visual-studio - "code ."命令无法从 mac 终端打开 Visual Studio Code 操作符