2016-11-11 52 views
0

我的OpenGL函数glutSpecialFunc需要一个带有3个int参数的void函数指针。这是很容易通过简单地OpenGL指向glutSpecialFunc到成员函数

glutSpecialFunc(processArrowKeys); 

与全局函数做的,但我想它指向一个成员函数在一个结构在另一个文件中,像这样:

inputs.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; 
    } 

} 

}; 

的main.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; 
} 

任何想法如何解决这个编译器错误?

回答

2

你不能直接这样做,因为成员函数有一个隐含的这个指针必须以某种方式通过调用链传递。相反,你创建的中介功能,将呼叫转接至正确的位置:

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); 
    // ... 
} 
+0

我明白了,谢谢<3 –