关于std::bind绑定成员函数与虚函数的方法

关于std::bind绑定成员函数与虚函数的方法。

  1. #include <iostream>

  2. #include <functional>

  3. using namespace std;

  4.  
  5. class A

  6. {

  7. public:

  8.     A() :m_a(0){}

  9.     ~A(){}

  10.  
  11.     virtual void SetA(const int& a){ cout << "A:" << this << endl;  m_a = a; }

  12.     int GetA()const { return m_a; }

  13. protected:

  14.     int m_a;

  15. };

  16. class B: public A

  17. {

  18. public:

  19.     B():A(){;}

  20.     ~B(){;}

  21.     virtual void SetA(const int& a){ cout << "B:" << this << endl; m_a = a; }

  22. private:

  23. };

  24.  
  25. int main(void)

  26. {

  27.     A a;

  28.     cout << "A:" << &a << endl;//0

  29.     function<void(const int&)> func1 = std::bind(&A::SetA, a, std::placeholders::_1);

  30.     func1(1);

  31.     cout << a.GetA() << endl;//0

  32.     function<void(const int&)> func2 = std::bind(&A::SetA, &a, std::placeholders::_1);

  33.     func2(2);

  34.     cout << a.GetA() << endl;//2

  35.  
  36.     cout << "---------" << endl;

  37.     A* pa = new B();

  38.     cout << "B:" << pa << endl;//0

  39.     function<void(const int&)> func3 = std::bind(&A::SetA, pa, std::placeholders::_1);

  40.     func3(3);

  41.     cout << pa->GetA() << endl;//3

  42.     function<void(const int&)> func4 = std::bind(&A::SetA, *pa, std::placeholders::_1);

  43.     func4(4);

  44.     cout << pa->GetA() << endl;//3

  45.     delete pa;

  46.     system("pause");

  47.     return 0;

  48. }

输出是:

 

由输出可以看出:

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支持虚函数。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值