关于std::function和std::bind绑定成员函数

std::function和std::bind绑定成员函数 | 火苗999℃的博客

#include <iostream>
#include <functional>
using namespace std;

class A
{
public:
    A() :m_a(0){}
    ~A(){}

    virtual void SetA(const int& a){ cout << "A:" << this << endl;  m_a = a; }
    int GetA()const { return m_a; }
protected:
    int m_a;
};
class B: public A
{
public:
    B():A(){;}
    ~B(){;}
    virtual void SetA(const int& a){ cout << "B:" << this << endl; m_a = a; }
private:
};

int main(void)
{
    A a;
    cout << "A:" << &a << endl;//0
    function<void(const int&)> func1 = std::bind(&A::SetA, a, std::placeholders::_1);
    func1(1);
    cout << a.GetA() << endl;//0
    function<void(const int&)> func2 = std::bind(&A::SetA, &a, std::placeholders::_1);
    func2(2);
    cout << a.GetA() << endl;//2

    cout << "---------" << endl;
    A* pa = new B();
    cout << "B:" << pa << endl;//0
    function<void(const int&)> func3 = std::bind(&A::SetA, pa, std::placeholders::_1);
    func3(3);
    cout << pa->GetA() << endl;//3
    function<void(const int&)> func4 = std::bind(&A::SetA, *pa, std::placeholders::_1);
    func4(4);
    cout << pa->GetA() << endl;//3
    delete pa;
    system("pause");
    return 0;
}

输出是:

由输出可以看出:

1、func1调用时产生了一个临时对象,然后调用临时对象的SetA;

2、func2调用的是a.SetA,改变了对象a中m_a的值;

3、func3调用的是pa->SetA,输出B:0060A4A8,调用的时B的SetA改变了pa->m_a;

4、func4调用时产生了一个临时对象,然后调用临时对象的A::SetA;

结论:std::bind中第二个参数应该是对象的指针,且std::bind支持虚函数。


 

  • 9
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值