I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

 

class A;

/******************************************************************************
/* 定义成员函数指针
/*****************************************************************************
*/
/* 
*  写成函数指针typedef void (*fp)(int a, int b);
*  会报错 error C2440: 'initializing' : cannot convert from '' to 'void (__cdecl *)(int,int)'
*/
typedef 
void (A::*mfp)(int a, int b);
typedef 
struct
{
    
int sth;
    mfp p;
}T_MAPPING;

/******************************************************************************
/* 类的声明
/*****************************************************************************
*/
class A
{
public:
    A() {}
    
~A() {}
    
void fa(int a, int b);
    
void fb(int a, int b);
    
void fc(int a, int b);
    
void test();
};

 

 

#include <stdio.h>
#include 
"fp.h"

/******************************************************************************
/* 成员函数实现
/*****************************************************************************
*/
void A::fa(int a, int b)
{
    printf(
"A::fa() a = %d, b = %d\n", a, b);
}

void A::fb(int a, int b)
{
    printf(
"A::fb() a = %d, b = %d\n", a, b);
}

void A::fc(int a, int b)
{
    printf(
"A::fc() a = %d, b = %d\n", a, b);
}


/******************************************************************************
/* 成员函数指针的使用
/*****************************************************************************
*/
void A::test()
{
    T_MAPPING a[]
=
    {
        {
10, &A::fa},
        {
20, &A::fb},
        {
30, fc},
    };

    
for (int idx = 0; idx < sizeof(a)/sizeof(a[0]); idx++)
    {
        
/* 
        *  函数指针和类成员函数指针的区别是使用类成员函数指针时需要加this指针
        *  调用格式写成(a[idx].p)(idx, 2 * idx);
        *  则会报错 error C2064: term does not evaluate to a function
        
*/
        (
this->*a[idx].p)(idx, 2 * idx);
    }
}

 

posted on 2011-05-25 23:34  jcsu  阅读(929)  评论(0)    收藏  举报