桌面计算器——可调用对象练习

#include <iostream>
#include <map>
#include <functional>

using namespace std;

map<string, function<int (int, int)>> binops;

class multiply {
public:
	int operator()(int a, int b) const { return a * b; }
};

int add(int a, int b)
{
	return a + b;
}

auto divide = [](int a, int b) { return a / b; };

void func()
{
	binops.insert({"+", add});
	binops.insert(make_pair("-", minus<int>()));
	binops.insert(pair<string, function<int (int, int)>>("*", multiply()));
	binops.insert(map<string, function<int (int, int)>>::value_type("/", divide));
	binops.insert({"%", [](int a, int b) { return a % b; }});
}

int main()
{
	func();
	cout << "请按照此形式(如:a + b)输入计算表达式:\n";
	int a, b;
	string s;
	while (cin >> a >> s >> b) {
		cout << binops[s](a, b) << endl;
		cout << "请按照此形式(如:a + b)输入计算表达式:\n";
	}
	return 0;
} 

  

posted @ 2017-11-17 13:26  GGBeng  阅读(209)  评论(0编辑  收藏  举报