C++闭包示例

本文深入探讨了C++中的闭包概念,详细解释了闭包的定义、作用及其实现方式,并通过实例代码展示了如何在C++中创建和使用闭包,帮助读者理解闭包在函数式编程中的应用。
摘要由CSDN通过智能技术生成
#include <iostream>
using namespace std;


auto mpaip(int a, int b) {    // 函数的返回值是一个函数
	return [a, b](auto c) {return c(a, b); };
}
int first(int a, int b) { return a; }
int second(int a, int b) { return b; }

int main()
{
	auto pp = mpaip(1, 2);   //返回一个变量pp,是一个函数
	auto pa = pp(first);     // auto pa=mpair(1,2)(first);
	auto pb = pp(second);

	cout << pa << ":" << pb << endl;   //1:2

	auto pp2 = mpaip(3, 4);   //返回一个变量pp,是一个函数
	auto pa2 = pp2(first);     // auto pa=mpair(3,4)(first);
	auto pb2 = pp2(second);

	cout << pa2 << ":" << pb2 << endl;   //3:4

	getchar();
	return 0;
}


#include <iostream>
using namespace std;

int main()
{
	auto f = [](int in) {
		int t = 3;
		return [=](int x) {return in + t + x; };
	};

	auto fx = f(3);
	auto f1 = fx(4);
	auto f2 = fx(5);
	cout << f1 << ":" << f2 << endl;   //10:11  (3+3+4:3+3+5)

	getchar();
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亭台六七座

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值