C++11 函数调用操作符重载 function 加减乘除四则运算计算器

function+bind可以实现按值传递函数对象

从而而消灭多态(无需继承基类即可实现一般意义上的多态)

本质上是对象消息机制,可以向任何对象传递消息并执行,只需要规定消息的格式,这个格式就是函数对象的声明。

本文示例代码:参考《C++ Primer 第五版中文版》 

思想参考:《Linux 多线程服务端编程》以及 孟岩的  function/bind的救赎(上)

另见:面向接口编程

代码:

#include <map>
#include <iostream>
#include <string>
#include <functional>
using namespace std;

int add(int i, int j) { return i + j; }

class divide
{
public:
    int operator()(int i, int j) { return i / j; }
};

class Big
{
public:
    bool bigger_than(int i, int j) { return i > j; }
};
int main(int, char *[])
{
    int i = 10, j = 5;

    auto mod = [](int i, int j) {return i % j; };
    typedef function<int(int, int)> fun;
    map<string, function<int(int, int)>> binary_operators;

    binary_operators.insert(make_pair<string, fun>("+", add));//函数指针
    binary_operators.insert(make_pair<string, fun>("-", std::minus<int>()));//函数对象
    binary_operators.insert(make_pair<string, fun>("/", divide()));//用户定义的函数对象
    binary_operators.insert(make_pair<string, fun>("*", [](int i, int j) {return i * j; }));//未命名的lambda
    binary_operators.insert(make_pair<string, fun>("%", mod));//命了名的lambda
    Big big;
    auto f = std::bind(&Big::bigger_than, big, std::placeholders::_1, std::placeholders::_2);//调用big.bigger_than(i,j)
    binary_operators.insert(make_pair<string, fun>(">", f));//任意类的成员函数

    cout << i << "+" << j << "=" << binary_operators["+"](i, j) << endl;
    cout << i << "-" << j << "=" << binary_operators["-"](i, j) << endl;
    cout << i << "/" << j << "=" << binary_operators["/"](i, j) << endl;
    cout << i << "*" << j << "=" << binary_operators["*"](i, j) << endl;
    cout << i << "%" << j << "=" << binary_operators["%"](i, j) << endl;
    cout << i << ">" << j << "=" << binary_operators[">"](i, j) << endl;
    return 0;
};

输出:

10+5=15
10-5=5
10/5=2
10*5=50
10%5=0
10>5=1
请按任意键继续. . .



 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值