我想为 C++ 中的简单游戏实现一个带有函数指针的简单事件接口。这样做是为了改进 allegro lib 的事件接口。因此,我编写了以下代码,但它不起作用。
typedef void (*event_handler)(int); //type for the event handler
const int TESTKEY_A = 1; // example Key as event arg
class Game
{
private:
bool is_running ;
protected:
event_handler on_key_down[2];
public:
void run();
void do_events(int e) ;
void stop() {is_running = false;}
};
void Game::run()
{
is_running=true;
while(is_running)
do_events(1);
}
void Game::do_events(int e)
{
if(e==1)
{
for(int i = 0; i < 2 ;i++)
on_key_down[i](TESTKEY_A);
}
}
class Pong_Game : public Game
{
public:
Pong_Game();
void On_Key_Down_Player1(int key) { return;}
void On_Key_Down_Player2(int key) { return;}
};
Pong_Game::Pong_Game()
{
on_key_down[0] = &this->On_Key_Down_Player1;
on_key_down[1] = &this->On_Key_Down_Player2;
}
int main()
{
Game *my_game = new Pong_Game();
my_game->run();
return 0;
}
编译器日志:
Compiler: Default compiler
Executing g++.exe...
g++.exe "U:\Eigene Dateien\eventhandler.cpp" -o "U:\Eigene Dateien\eventhandler.exe" -I"C:\Dev-Cpp\lib\gcc\mingw32\3.4.2\include" -I"C:\Dev-Cpp\include\c++\3.4.2\backward" -I"C:\Dev-Cpp\include\c++\3.4.2\mingw32" -I"C:\Dev-Cpp\include\c++\3.4.2" -I"C:\Dev-Cpp\include" -L"C:\Dev-Cpp\lib"
U:\Eigene Dateien\eventhandler.cpp: In constructor `Pong_Game::Pong_Game()':
U:\Eigene Dateien\eventhandler.cpp:45: error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say `&Pong_Game::On_Key_Down_Player1'
U:\Eigene Dateien\eventhandler.cpp:45: error: cannot convert `void (Pong_Game::*)(int)' to `void (*)(int)' in assignment
U:\Eigene Dateien\eventhandler.cpp:46: error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say `&Pong_Game::On_Key_Down_Player2'
U:\Eigene Dateien\eventhandler.cpp:46: error: cannot convert `void (Pong_Game::*)(int)' to `void (*)(int)' in assignment
Execution terminated
编辑: - 更改代码 - 添加编译器日志
谢谢!