我有一些简单的C风格代码,它实现了一个简单的命令解释器,如下所示:
typedef struct {
char *name;
int (*func)(char* args);
} sCOMMAND;
int func_reset(char* args);
int func_acc(char* args);
int func_dec(char* args);
const sCOMMAND CmdTbl[] = {
{ "RST", func_reset },
{ "ACC", func_acc },
{ "DEC", func_dec }
};
void ProcessCommand (char *cCmd)
{
int ndx = NUM_CMDS;
// shortest cmd is 3 chars
if (strlen(cCmd) >= MIN_CMD_LEN)
{
/////////////////////////////////////////////////////
// Chop the command line into substrings with ptr to
// each one where *parm[0] points to the command.
char *parms[MAX_PARMS];
ParseCommand(cCmd, parms);
/////////////////////////////////////////////////////
// Scan the command table looking for a match
for (int ndx = 0; ndx < NUM_CMDS; ndx++)
{
if (stricmp (CmdTbl[ndx].name, &parms[0]) == 0)
{
// command found, run its function
CmdTbl[ndx].func(parms);
}
}
}
// no valid command was found
if (ndx == NUM_CMDS)
Serial.println("UNKNOWN COMMAND");
Serial.println("RDY> ");
}
这很有用,但我想做的是将命令解释器封装在C ++类中。但是我无法使用类方法设置sCOMMAND表。我最近的尝试是:
//在文件CmdHandler.h中
class CmdHandler;
typedef struct {
char *name;
int (CmdHandler::*func)(char* args);
} sCOMMAND;
class CmdHandler
{
public:
CmdHandler(int buf_size);
~CmdHandler(void) { if (m_Buf) delete [] m_Buf; };
void ProcessCommand (char *cCmd);
private:
char *m_Buf;
int m_BufSize;
char *parms[MAX_PARMS];
void ParseCommand(char *cCmd, char* (&parms)[MAX_PARMS]);
int func_1(char* args);
int func_2(char* args);
int func_3(char* args);
sCOMMAND CmdTbl[3];
};
//在文件CmdHandler.cpp中
#include "CmdHandler.h"
CmdHandler::CmdHandler(int buf_size)
: CmdTbl{ {"RST", func_1},
{"ACC", func_2},
{"DEC", func_3} }
{
m_BufSize = buf_size;
m_Buf = new char[m_BufSize];
}
void CmdHandler::ProcessCommand (char *cCmd)
{
}
在ARM GCC CPP编译器上,这会产生错误"cannot convert 'CmdHandler::func_1' from type 'int (CmdHandler::)(char*)' to type 'int (CmdHandler::*)(char*)'".
如果我将结构中的指针引用作为:
typedef struct {
char *name;
int (CmdHandler::func)(char* args);
} sCOMMAND;
我得到了
"CmdHandler.h: invalid use of incomplete type 'class CmdHandler'
int (CmdHandler::func)(char* args);".
有谁能告诉我如何解决这个问题,或建议更好的方法?
答案 0 :(得分:0)
与非成员函数不同,成员函数不会衰减到函数指针。因此,您需要使用:
CmdHandler::CmdHandler(int buf_size)
: cmd_tbl{ {"RST", &CmdHandler::func_1},
{"ACC", &CmdHandler::func_2},
{"DEC", &CmdHandler::func_3} }
{
m_BufSize = buf_size;
m_Buf = new char[m_BufSize];
}