// 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; }