64,682
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <functional>
#include <string>
using namespace std;
class Foo
{
public:
Foo();
~Foo();
Foo(const Foo& other);
Foo& operator = (const Foo& other);
public:
void methodA();
void methodB(int num);
void methodC(string& name);
private:
int number_;
};
Foo::Foo()
{
number_ = 0;
}
Foo::~Foo()
{
number_ = 100;
}
Foo::Foo(const Foo& other)
{
number_ = other.number_;
}
Foo& Foo::operator = (const Foo& other)
{
if (this == &other)
return *this;
number_ = other.number_;
return *this;
}
void Foo::methodA()
{
cout << __FUNCTION__ << endl;
number_ = 1000;
}
void Foo::methodB(int num)
{
cout << __FUNCTION__ << endl;
number_ = 1000;
cout << number_ + num << endl;
}
void Foo::methodC(string& name)
{
cout << __FUNCTION__ << endl;
cout << name << endl;
number_ = 1000;
cout << number_ << endl;
}
std::function<void()> functor;
int main()
{
//foo后,为什么functor()还能正确执行
//如果functor中被绑定的是一个copy的Foo对象,但是没有调用copy函数
{
Foo foo;
functor = std::bind(&Foo::methodA, &foo);
}
functor();
{
Foo foo;
functor = std::bind(&Foo::methodB, &foo, 100);
}
functor();
{
Foo foo;
functor = std::bind(&Foo::methodC, &foo, string("Foo"));
}
functor();
return 0;
}