C++算术仿函数

1.

仿函数就是仿造的函数,它并不是一个真正意义上的函数。它是一个类中的运算符()重载,但它具有函数的功能;算术仿函数为了不重复造轮子,C++提供了一套算术仿函数;算术运仿函数的功能就是实现四则运算,其中取反运算negate是一元运算,其他都是二元运算,算术仿函数的原型如下:

template<class T> T plus<T>     //加法仿函数
template<class T> T minus<T>    //减法仿函数
template<class T> T multiplies<T>//乘法仿函数
template<class T> T divides<T>   //除法仿函数
template<class T>T modulus<T>  //取模仿函数
template<class T> T negate<T>   //取反仿函数

需要包含的头文件:

#include <functional>

示例代码:

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

using namespace std;

void test01(void)
{
	negate<int> n1;
	cout <<"取反:"<<endl<< n1(50) << endl;

	plus<float> p1;
	cout <<"加法:"<<endl<< p1(1.13,2.13) << endl;

	minus<int> m1;
	cout <<"减法:"<<endl<< m1(14,2) << endl;

	multiplies<float> mu1;
	cout <<"乘法:"<<endl<< mu1(3.1,2.1) << endl;
	
	divides<float> d1;
	cout <<"除法:"<<endl<< d1(3.1,1.1) << endl;

	modulus<int> mo1;
	cout <<"取模:"<<endl<< mo1(32,3) << endl;
}

int main(void)
{
	test01();

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值