std::bind可以绑定成员变量

#include <iostream>
#include <string>
#include <functional>

using namespace std;

class MyClass
{
public:
	MyClass(){}
	MyClass(int a): m_i(a){}
	~MyClass(){}

	void Get(int a, string str)
	{
		cout << a << " " << str << endl;
	}
public:
	int m_i;
};

// 绑定成员函数
void Test_Bind_Member_Func()
{
	MyClass myclass(2);// std::placeholders::_1
	std::function<void(int, string str)> m_fun = std::bind(&MyClass::Get, &myclass, 100, std::placeholders::_2);	// 这里是封装的返回值是引用类型才可以修改类的成员函数
	if (m_fun)
	{
		m_fun(111, "acb"); // 输出111 abc
	}
}


// 一种特殊场景,可以绑定类的成员变量,可以通过函数调用的方式访问和修改它
// 可以修改的前提是,可调用对象封装器封装的函数返回值是引用类型
void Test_Bind_Member_Variable()
{
	MyClass myclass(2);
	std::function<int&(void)> m_v = std::bind(&MyClass::m_i,&myclass);	// 这里是封装的返回值是引用类型才可以修改类的成员变量
	if (m_v)
	{
		cout << "m_v: " << m_v() << endl;
		m_v() = 3;															// 相当于修改成员变量
		cout << "m_v: " << m_v() << endl;
	}
}

int TestFunc(int a, char c, float f)
{
	cout << a << endl;
	cout << c << endl;
	cout << f << endl;

	return a;
}

void Test()
{
	auto bindFunc1 = bind(TestFunc, std::placeholders::_1, 'A', 100.1);
bindFunc1(10);

cout << "=================================\n";

auto bindFunc2 = bind(TestFunc, std::placeholders::_2, std::placeholders::_1, 100.1);
bindFunc2('B', 10);

cout << "=================================\n";

auto bindFunc3 = bind(TestFunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);
bindFunc3(100.1, 30, 'C');
}


int main()
{
	Test_Bind_Member_Func();		// 绑定成员函数
	Test_Bind_Member_Variable();	// 绑定成员变量

	getchar();
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值