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

  转载自:

    https://blog.csdn.net/defaultbyzt/article/details/47102175

 

  

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

 

[cpp] view plain copy
 
  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支持虚函数。

posted @ 2018-04-23 18:22  博客园—哆啦A梦  阅读(2024)  评论(0)    收藏  举报