C++中函數指針的用法

// TestFuncPtr.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//*************begin********************
typedef int (*FUNCPTR)(int a, int b);
int Add(int a, int b)
{
 return a + b;
}
int Sub(int a, int b)
{
 return a - b;
}
class MyMathUtil;
// define the class function pointer type
typedef int (MyMathUtil::*CLS_FUNC_PTR)(int a, int b);
class MyMathUtil
{
public:
 int Add(int a , int b) { return a + b;}
 int Sub(int a , int b) { return a - b;}
 int Operation(int a , int b)
 {
  int r;
  r = (this->*m_pFuncPtr)(a, b);
  return r;
 }
public:
 CLS_FUNC_PTR m_pFuncPtr;
};
//*************end**********************
int _tmain(int argc, _TCHAR* argv[])
{
 FUNCPTR ptr = NULL; 
 ptr = &Add; //or: ptr = Add; directly
 int r = (*ptr)(1, 2);
 MyMathUtil mathUtil;
 CLS_FUNC_PTR clsFuncPtr = NULL;
 clsFuncPtr = &MyMathUtil::Add; // Here, we must use &
 r = (mathUtil.*clsFuncPtr)(1, 2); // Here, we must use () for mathUtil.*clsFuncPtr
 mathUtil.m_pFuncPtr = &MyMathUtil::Sub;
 r = mathUtil.Operation(1, 2); // It can work like this
 //((&mathUtil)->*m_pFuncPtr)(1,2); // It's wrong!!!
 return 0;
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章