STL函数对象基本使用

这篇博客探讨了C++中的函数对象,即functor的使用。通过实例展示了如何定义和使用自定义的函数对象,包括带有状态的函数对象。同时,文章提到了函数对象可以作为参数传递,增强了代码的灵活性。在test01、test02和test03函数中,详细演示了函数对象的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

黑马237
#include
#include
#include
#include
#include
using namespace std;
//函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
class myClass
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
//函数对象超出普通函数的概念,函数对象可以有自己的状态
class myPrint
{
public:
myPrint()
{
this->count = 0;
}
void operator()(string test)
{
cout << test << endl;
count++;
}
int count;//拥有自己的状态
};
void test01()
{
myClass add;
cout << add(10, 10) << endl;
}
void test02()
{
myPrint myprint;
myprint(“hello”);
myprint(“hello”);
myprint(“hello”);
cout << “调用次数:” << myprint.count << endl;
}
//函数对象可以作为参数传递
void doPrint(myPrint& mp, string test)
{
mp(test);
}
void test03()
{
myPrint myprint;
doPrint(myprint, “hello C++”);
}
int main()
{
test03();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值