类和对象 第五部分第六小节:函数调用运算符重载

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();
}

我们可以直接通过调用匿名函数对象的方式来直接实现函数运算

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值