函数调用运算符:小括号()也可以重载。
由于重载后使用的方式非常像函数的调用,因此称为仿函数。STL中用的较多。
仿函数没有固定写法,非常灵活。
#include<iostream>
using namespace std;
#include<string>
// 函数调用运算符重载
class MyPrint
{
public:
// 重载函数调用运算符
void operator()(string str)
{
cout << str << endl;
}
};
void test01()
{
MyPrint myPrint;
myPrint("it looks like a function."); // 非常像一个函数。因此叫仿函数。
}
// 仿函数非常灵活,没有固定写法。依照需求,写对应的仿函数。在STL中会写大量的仿函数。
class MyAdd
{
public:
int operator()(int num1, int num2)
{
return num1 + num2;
}
};
void test02()
{
MyAdd myadd;
int sum = myadd(10, 20);
cout << "sum = " << sum << endl;
// 补充知识点:
// 匿名函数对象
cout << MyAdd()(100, 200) << endl; // MyAdd()这是为了创建匿名对象。然后调用函数运算符。
// 类名加小括号,会创建一个匿名对象。
}
int main()
{
test01();
system("pause");
return 0;
}
在STL中会经常用到。
补充知识点:匿名函数对象
类名加小括号:会创建一个匿名对象。对象就可以继续调用重载的函数调用运算符。
本文介绍了C++中函数调用运算符的重载方法,解释了如何通过重载实现仿函数,并展示了如何创建和使用匿名函数对象。通过具体示例说明了仿函数的灵活性及其在STL中的应用。
475

被折叠的 条评论
为什么被折叠?



