qt5 lamda表达式
时间: 2023-10-20 20:05:48 浏览: 114
Lambda表达式是C++11引入的一个新特性,它允许在需要函数对象的地方使用一个可以被隐式转换成函数指针的匿名函数。
在Qt5中,Lambda表达式被广泛应用于信号与槽的连接中,用于简化连接代码。
例如,我们可以使用Lambda表达式来连接QPushButton的clicked信号,代码如下:
```cpp
QPushButton *button = new QPushButton("Click me");
connect(button, &QPushButton::clicked, [](){
qDebug() << "Button clicked";
});
```
上述代码中,我们使用Lambda表达式作为槽函数,当QPushButton的clicked信号被触发时,Lambda表达式中的代码将被执行。
Lambda表达式的一般语法为:
```cpp
[capture list](parameter list) mutable(optional) exception attribute -> return type { function body }
```
其中,capture list是捕获列表,用于捕获外部变量;parameter list是参数列表,用于定义Lambda表达式的参数;mutable关键字用于指定Lambda表达式是否可以修改捕获的变量;exception attribute用于指定异常规范;return type用于指定返回值类型;function body是Lambda表达式的函数体。
Lambda表达式的捕获列表可以使用以下方式:
- []:不捕获任何变量。
- [var]:捕获变量var,变量可以是局部变量、全局变量或静态变量。
- [&var]:以引用的方式捕获变量var。
- [=]:以值的方式捕获所有外部变量。
- [&]:以引用的方式捕获所有外部变量。
Lambda表达式的参数列表与普通函数的参数列表一样,可以包含任意数量的参数,并且参数类型可以省略,由编译器自动推导。在Lambda表达式中,参数可以使用auto关键字代替参数类型。
Lambda表达式的返回类型可以省略,由编译器自动推导。如果函数体中只有一条语句,可以省略函数体的花括号;如果函数体为空,可以省略函数体。
Lambda表达式的应用非常广泛,除了信号与槽的连接之外,还可以用于STL算法、多线程编程等方面。
阅读全文
相关推荐















