function
为什么需要function?绑定器、函数对象、lambda表达式 他们只能使用在一条语句中
如果我们想在多条语句中应用这些函数对象 需要function将这些函数对象的类型留下来实现条件:
1.需要用函数类型来实例化function2.只给出返回值和参数列表
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; }