成員函式指針

成員函式指針是屬於函式指針,在C++中用.*和->*操作符來綁定到實際的對象。

基本介紹

  • 中文名:成員函式指針
  • 屬於:函式指針
  • 綁定:到實際的對象
  • 引用:獲取成員;
函式指針,成員函式指針,靜態成員函式指針,簡單例子,

函式指針

成員函式指針

1.成員函式指針通過引用操作符(.*)從對象或引用獲取成員;
2.成員函式指針通過箭頭操作符(->*)從對象指針獲取成員。
比如:
char(Screen::*pf)()const=&Screen::get;
其中get()為類Screen的成員函式;
Screen mScreem;
Screen *pScreen=&mScreem;
(pScreen->*pf)();相當於調用get;

靜態成員函式指針

靜態函式指針的調用和聲明方法,和普通的函式指針相同。

簡單例子

#include <stdio.h>
class CFuncPointer;
typedef void (CFuncPointer:: *pcfunc)(int,int);
typedef void (*pcstaticfunc)(int,int);
class CFuncPointer
{
public:
void Bind(pcfunc func)
{
m_runFunc = func;
}
void BindStatic(pcstaticfunc func)
{
m_staticFunc = func;
}
void pa(int x, int y)
{
printf("<CFuncPointer>[pa_]%d, %d\n", x, y);
}
void pb(int x, int y)
{
printf("<CFuncPointer>[pb__]%d, %d\n", x, y);
}
void pc(int x, int y)
{
printf("<CFuncPointer>[pc___]%d, %d\n", x, y);
}
static void pstatica(int x, int y)
{
printf("<CFuncPointer>[statica_]%d, %d\n", x, y);
}
static void pstaticb(int x, int y)
{
printf("<CFuncPointer>[staticb__]%d, %d\n", x, y);
}
void worker()
{
(this->*m_runFunc)(1, 2);
}
void sworker()
{
(*m_staticFunc)(1, 2);
}
private:
pcfunc m_runFunc;
pcstaticfunc m_staticFunc;
};
int main(int argc, char* argv[])
{
CFuncPointer *pclPoint=new CFuncPointer();
pclPoint->Bind(&CFuncPointer::pa);
pclPoint->worker();
pclPoint->Bind(&CFuncPointer::pb);
pclPoint->worker();
pclPoint->Bind(&CFuncPointer::pc);
pclPoint->worker();
pclPoint->BindStatic(CFuncPointer::pstatica);
pclPoint->sworker();
pclPoint->BindStatic(CFuncPointer::pstaticb);
pclPoint->sworker();
delete pclPoint;
return 0;
}
輸出結果:
<CFuncPointer>[pa_]1, 2
<CFuncPointer>[pb__]1, 2
<CFuncPointer>[pc___]1, 2
<CFuncPointer>[statica_]1, 2
<CFuncPointer>[staticb__]1, 2

相關詞條

熱門詞條

聯絡我們