1. 程式人生 > >關於std::function和std::bind繫結成員函式

關於std::function和std::bind繫結成員函式

關於std::bind繫結成員函式與虛擬函式的方法。

#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支援虛擬函式。