在C中
#include "stdio.h"
int foo(int a)
{
printf("This is foo => %d\n",a);
}
int foo2(int a)
{
printf("This is foo2 => %d\n",a);
}
int main()
{
int (*pFunction)(int) = foo; //宣告pFunction指針是int (*)(int)函數指針且為初值為foo函數
pFunction(100); //<=印出 This is foo => 100
pFunction = foo2;
pFunction(200); //<=印出 This is foo2 => 200
return 0;
}
----------------------------------------------------------------------------------------------------------------------------
在C++的類別中
class Neo
{
public:
void (*pFun)();
void go(void);
};
在函式中可用void(Neo::*pFun)() = &Neo::go;指定函數
在同類別中用(this->*pFun)();來呼叫
-----------------------------------------------------------------------------------------------------------------------------
類別函數指標
class Neo
{
public:
void go1(void);
void go2(void);
}
//先宣告成員函數指標
typedef void (Neo::*pfun)();
//再宣告結構體的方式
typedef struct ActionStruct
{
ptr function;
char* name;
} AS;
接著再cpp先註冊函數表
AS Actions[] =
{
{ &Neo::go1, "go1"},
{ &Neo::go2, "go2"}
};
呼叫方式如下
(this->*(Actions[1].function))();
char *functionName = Actions[1].name;
沒有留言:
張貼留言