lambda的作用
用于定义并创建匿名的函数对象,以此来简化开发
语法
[capture](parameters)mutable->return-type{statement}
其中
1.[capture]:捕获列表(到定义位置的所有局部变量)[]不能省略
2.(paramenters)参数列表,与普通参数的参数列表是一致的。
3.mutable 可修改提示符 即使参数为空,参数列表()也不能省略
4.->return-type 返回值类型,不需要可以省略
5{statement}函数体,希望函数做什么事,可以是用参数列表,也可以使用捕获列表
多说无益,直接进行实战
lambda表达式实战
下面是一个最基础的lambda表达式
[](){
};
上面的一大堆,就表示一个函数
1.lambda基础用法
auto fun1=[](){
std::cout<<"最基础的lambda表达式"<<std::endl;
};
fun1();
2.传递局部变量
std::string a="局部变量被捕捉";
auto fun2=[a]()
{
std::cout<<"带有局部变量的lambda表达式"<<a<<std::endl;
};
fun2();
3.接受返回值
std::string a="局部变量被捕捉";
auto fun3=[a](std::string c ,std::string b){
std::string res=a+c+b;
return res;
};
std::cout<<fun3("作为参数的传递","接受返回值")<<std::endl;
4.修改传递过来的拷贝的形参
int st=100;
auto fun4=[st](int i) mutable{
st=i;
return st;
};
std::cout<<"通过添加mutable表示符修改了形参值为:"<<fun4(299)<<std::endl;
5.修改传递过来的实参
int st=100;
auto fun5=[&st](int i) mutable{
st=i;
return "";
};
std::cout<<"通过添加mutable表示符修改了实参值为:"<<st<<fun5(368)<<std::endl;
6.最终案例,作为按钮的槽函数
connect(button2,&QPushButton::clicked,this,[=](){this->close();std::cout<<"我接受到了所有的参数,其中,st:"<<st<<std::endl;});