C++ lambad表达式

lambad:就是一个返回函数指针的表达式,它定义和返回值函数指针放在一起。

lambad表达式的组成部分

        [捕获方式](函数参数)mutable exception ->函数返回值类型{函数体;};

捕获方式:

        [=]        //值的方式捕获

        [&]        //引用的方式捕获

        [this]     // this指针的方式捕获

        []          //不捕获任何变量

        [=,&x]        //混合方式捕获  x用引用的方式捕获,其他变量用值的方式捕获

mutable:说明lambad表达式可以修改捕获的值

exception:表示lambad是否可以抛出异常

#include<iostream>
using namespace std;

int Max(int a, int b)
{
	return a > b ? a : b;
}
void print(int(*pMax)(int, int), int a, int b)
{
	cout << pMax(a, b)<<endl ;
}
class MM
{
public:
	void print()
	{
		[this]{cout << name << age << endl; }();
	}
protected:
	string name = "默认";
	int age = 12;

};
int main()
{
	int(*pMax)(int, int) = nullptr;	//函数指针
	//完整写法
	pMax = [](int a, int b)mutable noexcept->int {return a > b ? a : b; };
	cout << pMax(1, 3) << endl;
	//省略写法
	auto pp = [](int a, int b)->int {return a > b ? a : b; };
	cout << pp(1, 3) << endl;
	//一步到位		短暂性局部使用的函数
	cout << [](int a, int b)->int {return a > b ? a : b; }(1, 2) << endl;	//定义与调用一步
	print([](int a, int b)->int {return a > b ? a : b; }, 2, 5);
	print([](int a, int b)->int {return a + b; }, 2, 5);

	//用值的方式捕获:在lambad中不能当做左值使用,函数调用不会因为值的 改变而改变。
	int data = 1111;
	auto pFunc = [=] {cout << data << endl; };	//无参可以省略()
	pFunc();
	data = 222;
	pFunc();	//值没有改变
	auto pFunc2 = [&] {cout << data << endl; };	//引用的方式捕获
	pFunc2();
	data = 888;
	pFunc2();	//引用 的方式可以改变
	//this的方式 捕获类中的对象
	MM mm;
	mm.print();
	// 结合 auto使用
	auto pAuto = [](auto a, auto b)-> auto{return a > b ? a : b; };
	cout << pAuto(1, 3) << endl;		//调用 auto根据实参a b推断类型
	cout << pAuto("stringa", "stringb") << endl;

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值