求问c++11中function绑定类成员变量的问题

zeqi1991 zeqi1991 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

#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;
}

...全文

相关推荐

C++中使用function和bind绑定类成员函数的方法详解

定义一个普通的类 class Test1{ public: void fun(int val){ cout&lt; pf = std::bind(&Test1::fun,t,2); pf(4); // return 0; } 输出的值是2,说明pf传进去的4并没有什么用,在bind的时候值已经绑定死了,但是pf()这样不给参数会报错。 如果我们想自定义参数,使用占位符,std::placeholders::_1,可以看

weixin_38687904

APIHook、InlineHook库,使用C++11编写,可将回调函数绑定到类成员函数

APIHook、InlineHook库,使用C++11编写,可将回调函数绑定到类成员函数。代码风格良好,适合学习。

HandOfSorrow

C++ 11 std::function和std::bind使用详解

主要介绍了C++ 11 std::function和std::bind使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

weixin_38689477

C++11中lambda、std::function和std:bind详解

大家都知道C++11中增加了许多的新特性,下面在这篇文中我们就来聊一下lambda表达式,闭包,std::function以及std::bind。文中介绍的很详细,相信对大家具有一定的参考价值,有需要的朋友们下面来一起看看吧。

weixin_38522529

C++ 包含类两个类互相调用彼此的类成员变量和方法

C++,C 包含类两个类互相调用彼此的类成员变量和方法,里面介绍了如何在头文件中创建相互的类对象,简单易懂

高祥xiang
评论 1
收藏 已收藏
分享
返回顶部
zeqi1991
C++ 语言 65,214 成员 250,514 内容