C++ 密钥绑定?(c)(将字符串转换为函数)
我正在为我的应用程序编写一个简单的键绑定。到目前为止,我有2个数组(布尔m_键[256],字符串m_函数) 这是我的输入类(在input.h中) 在我的帧函数中(每帧运行;)C++ 密钥绑定?(c)(将字符串转换为函数),c++,windows,string,casting,keyboard,C++,Windows,String,Casting,Keyboard,我正在为我的应用程序编写一个简单的键绑定。到目前为止,我有2个数组(布尔m_键[256],字符串m_函数) 这是我的输入类(在input.h中) 在我的帧函数中(每帧运行;) short-SystemClass::Frame() { 字符串函数; func=m_Input->IsKeyDown(VK_RETURN);//检查回车键是否已按下 if(func!=“”)(func as function)(;//IsKeyDown(VK_F2)!=“”)m_Graphics->ToggleWireF
short-SystemClass::Frame()
{
字符串函数;
func=m_Input->IsKeyDown(VK_RETURN);//检查回车键是否已按下
if(func!=“”)(func as function)(;//IsKeyDown(VK_F2)!=“”)m_Graphics->ToggleWireFrame();
如果(!m_Graphics->Frame())返回-1;
返回1;
}
如果我理解正确,您正在尝试从字符串获取可调用函数。C++缺乏,所以这样做真的是不可行的。你可以使用一些替代品
我的建议是让
InputClass::functions
数组包含函数指针,而不是字符串。然后可以将函数地址传递给AddFunc
,而不是字符串,并相应地设置给定的数组成员。对于非成员函数,这将非常有效。如果您希望能够调用类实例的成员函数,我会将InputClass::functions
设置为一个s数组,并将返回的functor传递到AddFunc
如果我理解正确,您是在尝试从字符串获取可调用函数。C++缺乏,所以这样做真的是不可行的。你可以使用一些替代品
我的建议是让
InputClass::functions
数组包含函数指针,而不是字符串。然后可以将函数地址传递给AddFunc
,而不是字符串,并相应地设置给定的数组成员。对于非成员函数,这将非常有效。如果您希望能够调用类实例的成员函数,我会将InputClass::functions
设置为一个s数组,并将返回的functor传递到AddFunc
中,请删除所有这些代码>在函数定义之后,正确缩进代码。请删除所有这些代码>在函数定义之后,正确缩进代码。如果使用字符串名称很重要,只需使用std::map
创建并(手动)维护有效名称到函数指针的映射。在任何情况下,使用std::map
而不是危险的数组。我会使用std::function
或std::function
,这取决于依赖项在代码中的工作方式。如果使用字符串名称很重要,请(手动)创建并使用std::map
维护有效名称到函数指针的映射。在任何情况下,使用std::map
而不是危险的数组。我会使用std::function
或std::function
,这取决于依赖项在代码中的工作方式。
class InputClass
{
public:
InputClass(){};
InputClass(const InputClass&){};
~InputClass(){};
void Initialize(){
for(int i=0; i<256; i++)
{
m_keys[i] = false;
functions[i] = "";
}
}
bool AddFunc(unsigned int key, string func, bool overide)
{
if((functions[key] == "") || (overide)){
//overide is used to overide the current string (if there is one)
functions[key] = func;
return true;
}
return false;
};
void KeyDown(unsigned int input){m_keys[input] = true;};
void KeyUp(unsigned int input){m_keys[input] = false;};
string IsKeyDown(unsigned int key){return m_keys[key] ? functions[key] : "";};
private:
bool m_keys[256];
string functions[256];
};
INIT(m_Input, InputClass) //#define INIT(o,c) if(!(o = new c))return false;
m_Input->Initialize();
m_Input->AddFunc(VK_RETURN,"m_Graphics->ToggleWireFrame",true);
short SystemClass::Frame()
{
string func;
func = m_Input->IsKeyDown(VK_RETURN); //checks to see if the enter key is down
if(func !="") (func as function)(); // <-- this is the code i need help with
if(m_Input->IsKeyDown(VK_F2)!="")m_Graphics->ToggleWireFrame();
if(!m_Graphics->Frame()) return -1;
return 1;
}