C++ 类的成员函数指针(用作函数参数) tcy

这个概念主要用在C++中去实现"委托"的特性. 
但现在C++11 中有了 更好用的function/bind 功能.
但对于类的成员函数指针的概念我们还是应该掌握的.

类函数指针 就是要确定由哪个 类的实例 去调用 类函数指针所指的函数

第一部分:函数指针 

float add(float a, float b) { return a + b; }
float sub(float a, float b) { return a - b; }

typedef float(*pf)(float, float);

float foo(float a, float b, pf op){
     float y = op(a, b);
     return y;
}

pf bar(const char* mode = "add") {
    if (mode == "add")
        return add;
    else
        return sub;
}

第二部分:类方法指针: 

class A {
public:
    int add(int x, int y) { return x + y; }
    int sub(int x, int y) { return x + y; }
    int mul(int x, int y)const { return x * y; }
    int div(int x, int y)const { return x / y; }
};

typedef int (A::*pfunc)(int, int) const;
//pfunc div1 = &A::div;

int Div(int x, int y,const A& self, pfunc op){
    return (self.*op)(x,y);
}

void test() {
    //测试1:
    int (A::*fp)(int, int) = &A::add;
    A a;
    cout << "1.1.add= " << (a.*fp)(10, 20) << endl;

    //测试2:
    typedef int (A::*f)(int, int);
    f add = &A::add;

    cout << "2.1.add=" << (a.*add)(10, 20) << endl;
    cout << "2.2.add=" << (a.*&A::add)(10, 20) << endl;
    cout << "2.3.add= " << (a.A::add)(10, 20) << endl;

    //测试3:
    int (A::*fp1)(int, int)const = &A::mul;
    cout << "3.1.add= " << (a.*fp1)(10, 20) << endl;

    //测试4:
    typedef int (A::*f1)(int, int) const;
    f1 mul = &A::mul;

    cout << "4.1.add=" << (a.*mul)(10, 20) << endl;
    cout << "4.2.add=" << (a.*&A::mul)(10, 20) << endl;
    cout << "4.3.add= " << (a.A::mul)(10, 20) << endl;

    //测试5:
    cout << "5.1.Div=" << Div(100, 2, a, &A::div) << endl;
}

int main(){
    test();
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值