函数指针 - 一般情况和类的nonstatic成员函数

函数指针是通过指向函数的指针间接调用函数。函数指针可以实现对参数类型、参数顺序、返回值都相同的函数进行封装,是多态的一种实现方式。由于类的非静态成员函数中有一个隐形的this指针,因此,类的成员函数的指针和一般函数的指针的表现形式不一样。

 

1、指向一般函数的指针

函数指针的声明中就包括了函数的参数类型、顺序和返回值,只能把相匹配的函数地址赋值给函数指针。为了封装同类型的函数,可以把函数指针作为通用接口函数的参数,并通过函数指针来间接调用所封装的函数。

下面是一个指向函数的指针使用的例子:

typedef int (*pFunc)(int, int);

int Max(int a, int b)
{
    return a>b ? a : b;
}

int Min(int a, int b)
{
    return a<b ? a : b;
}

int Result(pFunc fun, int a, int b)
{
    return (*fun)(a, b);
}

void main()
{
    int a = 3;
    int b = 4;
    cout << Result(Max, a, b) << endl;
    cout << Result(Min, a, b) << endl;
}

 

2、指向类的成员函数的指针

类的静态成员函数采用与一般函数指针相同的调用方式,而受this指针的影响,类的非静态成员函数与一般函数指针是不兼容的。而且,不同类的this指针是不一样的,因此,指向不同类的非静态成员函数的指针也是不兼容的。指向类的非静态成员函数的指针,在声明时就需要添加类名。

下面是一个指向类的成员函数的指针的使用的例子,包括指向静态和非静态成员函数的指针的使用:

 class CA;
typedef int (CA::*pClassFun)(int, int);
typedef int (*pGeneralFun)(int, int);

class CA
{
public:
    int Max(int a, int b){  return a > b ? a : b; }
    int Min(int a, int b){ return a < b ? a : b; }
    static int Sum(int a, int b){ return a + b; }

     int Result(pClassFun fun, int a, int b){ return (this->*fun)(a, b); }
};

int Result(CA* pA, pClassFun fun, int a, int b){  return (pA->*fun)(a, b); }

int GeneralResult(pGeneralFun fun, int a, int b){ return (*fun)(a, b); }

void main()
{
    CA ca;
    int a = 3;
    int b = 4;
    
    cout << "Test nonstatic member function pointer from member function:" << endl;
    cout << ca.Result(CA::Max, a, b) << endl;
    cout << ca.Result(CA::Min, a, b) << endl;

    cout<<"Test nonstatic member function pointer from external function:"<<endl;
    cout << Result(&ca, CA::Max, a, b) << endl;
    cout << Result(&ca, CA::Min, a, b) << endl;

    cout<<"Test static member function pointer: "<<endl;
    cout << GeneralResult(CA::Sum, a, b) << endl;
}


 


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值