1、函数调用运算符()可以重载 由于重载后使用方式非常像函数的调用,因此称此为仿函数
代码案例:打印输出仿函数
#include<iostream>
using namespace std;
class MyPrint
{
public://重载函数调用运算符void operator()(string text){cout << text << endl;}
};
void test01()
{//重载的()操作符 也称为仿函数MyPrint myFunc;myFunc("hello world");
}
int main()
{test01();
}
与真函数比较
#include<iostream>
using namespace std;
//真函数
void test02()
{cout << "hello world" << endl;
}int main()
{test02();
}
2.仿函数没有固定写法,非常灵活
代码案例:实现加法运算
#include<iostream>
using namespace std;
class MyAdd
{
public:int operator()(int v1, int v2){return v1 + v2;}
};
void test02()
{MyAdd add;int ret = add(10, 10);cout << "ret = " << ret << endl;
}int main()
{test02();
}
效果图:
额外:匿名函数对象
#include<iostream>
using namespace std;
class MyAdd
{
public:int operator()(int v1, int v2){return v1 + v2;}
};
void test02()
{MyAdd add;int ret = add(10, 10);//匿名对象调用 cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}int main()
{test02();
}
我们可以直接通过调用匿名函数对象的方式来直接实现函数运算