function函数对象机制

function


为什么需要function?绑定器、函数对象、lambda表达式 他们只能使用在一条语句中
如果我们想在多条语句中应用这些函数对象  需要function将这些函数对象的类型留下来

实现条件:
1.需要用函数类型来实例化function

2.只给出返回值和参数列表

void hello1()
{
	cout << "hello world!" << endl;
}
void hello2(string s)
{
	cout << s << endl;
}
int sum(int a, int b)
{
	return a + b;
}

class Test
{
public:  //必须依赖于一个对象
	void hello(string s)
	{
		cout << s << endl;
	}
};

int main()
{
	function<void()> func1 = hello1;
	func1;

	function<void(string)> func2 = hello2;
	func2("hello world!!!!!");

	function<int(int, int)> func3 = sum;
	cout << func3(20, 30) << endl;

	function<int(int, int)> func4 = [](int a, int b)->int {return a + b; };
	cout << func4(30, 40) << endl;

	//function 调用类的成员方法
	//void(Test*, string) 两个参数 一个是this指针对象 一个是参数
	function<void(Test*, string) > func5 = &Test::hello;
	//临时对象,打印内容
	func5(&Test(), "call Test::hello!");
}

 实际使用过程:

 

void doShowAllBooks() { cout << "查看所有书籍信息" << endl; }
void doBorrow() { cout << "借书" << endl; }
void doBack() { cout << "还书" << endl; }
void doQueryBooks() { cout << "查询书籍" << endl; }
void doLoginOut() { cout << "注销" << endl; }
void doend() { cout << "退出" << endl; }

int main()
{
	int choice = 0;

	map<int, function<void()>> actionMap;
	actionMap.insert({ 1, doShowAllBooks });//老版本:insert(make_pair(xx,xx));
	actionMap.insert({ 2, doBorrow });
	actionMap.insert({ 3, doBack });
	actionMap.insert({ 4, doQueryBooks });
	actionMap.insert({ 5, doLoginOut });
	actionMap.insert({ 6, doend });


	for (;;)
	{
		cout << "-----------------" << endl;
		cout << "1.查看所有书籍信息" << endl;
		cout << "2.借书" << endl;
		cout << "3.还书" << endl;
		cout << "4.查询书籍" << endl;
		cout << "5.注销" << endl;
		cout << "6.退出" << endl;
		cout << "-----------------" << endl;
		cout << "请选择:";
		cin >> choice;

		auto it = actionMap.find(choice);//map  pair  first second
		if (it == actionMap.end())
		{
			cout << "输入数字无效,重新选择!" << endl;
		}
		else
		{
			it->second();
		}
		
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值