C++筆記-Qt中使用Lambda時[]中的形式
阿新 • • 發佈:2021-02-01
有幾個地方要注意的:
[]這個表示Lambda的開始,如果要加引數可以這樣:[]()後面括號裡面放參數,Qt中connect中的訊號,引數
1. []:裡面為空,表示不使用任何引數物件的引數;
2. =:表示按值的方式進行傳遞;
3. &:表示以引用的方式進行傳遞;
4. this:表示函式體內可以使用Lambda所在類中的成員變數;
5. a:按值的方式進行傳遞,預設是不能修改的,如果要修改,需要新增mutable修飾符。
程式結構如下:
如下程式碼:
LambdaInQt.pro
QT -= gui CONFIG += c++11 console CONFIG -= app_bundle # The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ main.cpp # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target HEADERS += \ Test.h
Test.h
#ifndef TEST_H #define TEST_H #include <QObject> #include <QTimer> #include <QDebug> class Test1{ public: Test1(){ } Test1(const Test1 &test){ this->m_a = test.m_a; } Test1 &operator = (const Test1 &test){ this->m_a = test.m_a; } int m_a; }; class Test2{ public: int m_a; }; class MyEmit : public QObject{ Q_OBJECT public: MyEmit() : QObject(nullptr){ QTimer::singleShot(1000, [this](){ this->m_test1.m_a = 10; this->m_test2.m_a = 20; }); Test1 tmpTest1; tmpTest1.m_a = 100; QTimer::singleShot(1000, [=](){ this->m_a = 100; this->m_test1.m_a = 100; }); QTimer::singleShot(1000, [&](){ this->m_a = 100; tmpTest1.m_a = 300; }); int tmpa = 100; QTimer::singleShot(1000, [tmpa](){ qDebug() << tmpa; }); QTimer::singleShot(1000, [tmpTest1](){ qDebug() << tmpTest1.m_a; }); } signals: void sendSomeThing(); void sendToDoSomeThing(); private: int m_a; int m_b; Test1 m_test1; Test2 m_test2; }; #endif // TEST_H
main.cpp
#include <QCoreApplication> #include <QDebug> #include <QTimer> #include "Test.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyEmit myEmit; QTimer::singleShot(3000, [&]{ emit myEmit.sendSomeThing(); }); QEventLoop loop; QObject::connect(&myEmit, &MyEmit::sendSomeThing, [=](){ }); loop.exec(); qDebug() << "over"; return a.exec(); }