如何使用成員函式指標

李先靜發表於2020-04-06

很長時間沒有用過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[i], KeyAndHandlers[j].pszKey, KeyAndHandlers[j].nKeyLength) == 0)

                            {

                                     ParamHandler Handler = KeyAndHandlers[j].Handler;

                                     (this->*Handler)(argv[i] + 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;

}

        

 

相關文章