#include
#include
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 func1 = std::bind(&a::seta, a, std::placeholders::_1);
func1(1);
cout << a.geta() << endl;//0
function 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 func3 = std::bind(&a::seta, pa, std::placeholders::_1);
func3(3);
cout << pa->geta() << endl;//3
function 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支持虚函数。