2 回答

TA貢獻1785條經(jīng)驗 獲得超4個贊
public class Day1{ public static void main(String[] args){ int a = 1; a++;
System.out.println(a);} }
方法要放在類里面,方法的實現(xiàn)要放在方法里面

TA貢獻2021條經(jīng)驗 獲得超8個贊
就是創(chuàng)建臨時函數(shù)以方便重復(fù)調(diào)用,這個一般在局部函數(shù)中使用,不暴露在外部的。
auto是C/C++的東西,在C++11標(biāo)準的語法中,auto被定義為自動推斷變量的類型。
[](){}; 是在定義一個函數(shù),
記得怎么定義函數(shù)指針的么 typedef void (*FUNP)(int a); 類似的吧。
[]中括號里可以用&修飾,具體什么作用可以查查資料,我也不太清楚,在大部分情況下&符號不加也沒關(guān)系,但有時編譯器無法隱式捕獲;
()小括號中是形參列表;
{}括號中是函數(shù)體,
因為是定義函數(shù),大括號后面記得加 ; 分號。
例子:
void test()
{
auto fn = [&](int i){
printf("%d\n",i);
i++;
return i;
};
int var = 0;
while(var < 10000)
{
var = fn(var);
}
}
還有,利用此方法可以很方便的開辟線程
例子:之前用Qt寫的測試代碼,就沒重新寫例子
#include "thread"
#include <qmutex.h>
#include <QDebug>
#include <QTime>
long long tt = 0;
QMutex mtx;
int main(int argc, char *argv[])
{
std::thread *thd_test = new std::thread([&](){
bool quit = false;
while(!quit)
{
mtx.lock();
tt++;
if(tt== LLONG_MAX)
quit = true;
if(tt == 5000)
thd_test->detach();
mtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
});
std::thread *thd_run = new std::thread([&](){
bool exit = false;
while(!exit)
{
mtx.lock();
qDebug() << "thd_run" << tt;
if(tt == 10000)
exit = true;
mtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
thd_run->join();
qDebug() << "***********************************************";
std::this_thread::sleep_for(std::chrono::seconds(5));
qDebug() << "***********************************************";
std::thread *thd_after = new std::thread([&](){
bool exit = false;
while(!exit)
{
mtx.lock();
qDebug() << "thd_after" <<tt;
if(tt == 20000)
exit = true;
mtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
thd_after->join();
return 0;
}
- 2 回答
- 0 關(guān)注
- 79 瀏覽
添加回答
舉報