很长时间没有用过C++了,今天一位同事问我关于成员函数指针的问题。想了想,还是N年前用过一次,之后再也没有用过,印象不太深了。查了些资料,总终于想起来了,写一个例子在这里,以供以后查阅吧。
//build: gcc -g -lstdc++ mfp.cpp -o mfp.exe
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class CmdParaParser
{
public:
CmdParaParser();
~CmdParaParser();
public:
bool Parse(int argc, char* argv[]);
int GetWidth(void) const;
int GetHeight(void) const;
private:
bool ParseWidth(const char* value);
bool ParseHeight(const char* value);
private:
int m_nWidth;
int m_nHeight;
};
CmdParaParser::CmdParaParser()
{
m_nWidth = m_nHeight = 0;
return;
}
CmdParaParser::~CmdParaParser()
{
return;
}
bool CmdParaParser::Parse(int argc, char* argv[])
{
int i = 0;
int j = 0;
typedef bool (CmdParaParser::*ParamHandler)(const char* value);
struct KeyAndHandler
{
char* pszKey;
int nKeyLength;
ParamHandler Handler;
}
KeyAndHandlers[] =
{
{"--width=", sizeof("--width=") - 1, &CmdParaParser::ParseWidth},
{"--height=", sizeof("--height=") - 1, &CmdParaParser::ParseHeight},
{NULL, 0, NULL}
};
for(i = 1; i < argc; i++)
{
for(j = 0; KeyAndHandlers[j].pszKey != NULL; j++)
{
if(strncmp(argv, KeyAndHandlers[j].pszKey, KeyAndHandlers[j].nKeyLength) == 0)
{
ParamHandler Handler = KeyAndHandlers[j].Handler;
(this->*Handler)(argv + KeyAndHandlers[j].nKeyLength);
break;
}
}
}
return m_nWidth != 0 && m_nHeight != 0;
}
int CmdParaParser::GetWidth(void) const
{
return m_nWidth;
}
int CmdParaParser::GetHeight(void) const
{
return m_nHeight;
}
bool CmdParaParser::ParseWidth(const char* value)
{
m_nWidth = atoi(value);
return true;
}
bool CmdParaParser::ParseHeight(const char* value)
{
m_nHeight = atoi(value);
return true;
}
int main(int argc, char* argv[])
{
if(argc != 3)
{
printf("Usage: %s --width=n --height=n/n", argv[0]);
}
else
{
CmdParaParser aCmdParaParser;
aCmdParaParser.Parse(argc, argv);
printf("width=%d height=%d/n", aCmdParaParser.GetWidth(), aCmdParaParser.GetHeight());
}
return 0;
}
|