c++ —函数调用运算符重载
前言
c++中提供了函数调用运算符“()”的重载,重载后和普通的函数调用极其相似
所以又被称为仿函数
仿函数的创建非常灵活,所以这里只用两个例子来说明一下
上代码
#include<iostream>
#include<string>
using namespace std;
//函数调用运算符重载也叫作仿函数
class Print
{
public:
void operator()(string text)
{
cout << text << endl;
}
};
class Add
{
public:
int operator()(int a, int b)
{
int c = a + b;
return c;
}
};
void test01()
{
Print p;
p("hello world");
}
void test02()
{
Add a;
int ret = a(10, 20);
cout << ret << endl;
//匿名对象使用函数调用运算符重载
//匿名对象不需要建立具体对象,在函数使用完成后,系统会自动释放匿名对象
cout << Add()(10, 20) << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}