函数调用运算符重载
#include<bits/stdc++.h>
using namespace std;
//函数调用运算符重载
//打印输出类
class MyPrint
{
public:
//重载函数调用运算符
void operator()(string test)
{
cout<<test<<endl;
}
};
void test01()
{
MyPrint myPrint;
myPrint("hello world");//由于使用起来非常类似于函数调用,因此称为仿函数
}
//仿函数非常灵活,没有固定的写法
//加法类
class MyAdd
{
public:
int operator()(int num1,int num2)
{
return num1+num2;
}
};
void test02()
{
MyAdd myadd;
int ret=myadd(10,20);
cout<<ret<<endl;
//匿名函数对象
cout<<MyAdd()(10,20) <<endl;
}
int main(){
test01();
test02();
return 0;
}
匿名函数对象的使用的好处
-
临时性: 匿名函数对象可以在使用完毕后立即销毁,不会占用额外的命名空间,从而使代码更为简洁和清晰。
-
简洁性: 当一个函数对象只需要使用一次,没有必要为其命名,使用匿名函数对象可以避免定义额外的类或对象,减少代码量和复杂度。
-
便捷性: 匿名函数对象的创建和使用可以在一行代码中完成,非常适合于简单的函数对象调用,不需要额外的命名和定义步骤。
总结来说,匿名函数对象在实现简单的函数对象功能时非常方便,能够提高代码的可读性和简洁性,同时避免定义不必要的命名和额外的类对象。