我的 OpenGL 函数 glutSpecialFunc 需要一个带有 3 个 int 参数的 void 函数指针。这很容易通过简单的全局函数来完成
glutSpecialFunc(processArrowKeys);
但我想让它指向另一个文件中结构中的成员函数,如下所示:
输入.h
struct Keyboard {
bool leftMouseDown;
bool keyRight, keyLeft, keyUp, keyDown;
Keyboard() : leftMouseDown(false), keyRight(false), keyLeft(false), keyUp(false), keyDown(false) {
}
void Keyboard::processArrowKeys(int key, int x, int y) {
// process key strokes
if (key == GLUT_KEY_RIGHT) {
keyRight = true;
keyLeft = false;
keyUp = false;
keyDown = false;
}
else if (key == GLUT_KEY_LEFT) {
keyRight = false;
keyLeft = true;
keyUp = false;
keyDown = false;
}
else if (key == GLUT_KEY_UP) {
keyRight = false;
keyLeft = false;
keyUp = true;
keyDown = false;
}
else if (key == GLUT_KEY_DOWN) {
keyRight = false;
keyLeft = false;
keyUp = false;
keyDown = true;
}
}
};
主要.cpp
#include "inputs.h"
Keyboard keyboard;
...
int main(int argc, char **argv) {
...
// callbacks
glutDisplayFunc(displayWindow);
glutReshapeFunc(reshapeWindow);
glutIdleFunc(updateScene);
glutSpecialFunc(&keyboard.processArrowKeys); // compiler error: '&': illegal operation on bound member function expression
glutMouseFunc(mouseButton);
glutMotionFunc(mouseMove);
glutMainLoop();
return 0;
}
知道如何解决这个编译器错误吗?
最佳答案
你不能直接这样做,因为成员函数有一个隐式的 this 指针,它必须以某种方式通过调用链传递。相反,您创建一个中间函数,将调用转发到正确的位置:
void processArrowKeys(int key, int x, int y) {
keyboard.processArrowKeys(key, x, y);
}
int main() {
// ...
glutSpecialFunc(processArrowKeys);
// ...
}
您的代码中的 keyboard
似乎是全局的,因此它将起作用。如果你想拥有一个非全局状态,那么你将不得不使用一些 GLUT 实现支持的用户数据指针作为扩展(包括 FreeGLUT 和 OpenGLUT):
void processArrowKeys(int key, int x, int y) {
Keyboard *k = (Keyboard*)glutGetWindowData();
k->processArrowKeys(key, x, y);
}
int main() {
// ...
glutSpecialFunc(processArrowKeys);
glutSetWindowData(&keyboard);
// ...
}
关于c++ - OpenGL 将 glutSpecialFunc 指向成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40540823/