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;
}