2016-11-11 18 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 –