2014-01-13 118 views
0

我是新的使用c + + 11功能,也嘗試使用SDL_Widget-2 lib爲我的項目建立一個簡單的桂。但我被陷在問題:C++ 11 Lambda函數編譯錯誤

#include "sdl-widgets.h" 
class Builder 
{ 
    public: 
    Builder():top_win(nullptr) 
     ,but(nullptr) 
    { 
     top_win=new TopWin("Hello",Rect(100,100,120,100),0,0,false, 
      []() { 
      top_win->clear(); 
      draw_title_ttf->draw_string(top_win->render,"Hello world!",Point(20,40)); 
      } 
     ); 
     but=new Button(top_win,0,Rect(5,10,60,0),"catch me", 
      [](Button *b) { 
      static int dy=60; 
      b->hide(); 
      b->move(0,dy); 
      b->hidden=false; 
      dy= dy==60 ? -60 : 60; 
      }); 
    } 
private: 
    TopWin * top_win; 
    Button *but; 
}; 
int main(int,char**) { 
    Builder aViewBuilder; 
    get_events(); 
    return 0; 
} 

在編譯階段的錯誤:

在拉姆達功能:打印

error: 'this' was not captured for this lambda function 
error: 'this' was not captured for this lambda function 

此錯誤兩次INT控制檯。 我有嘗試:

[this](){} 

[=](){} 

[&](){} 

用不同的編譯錯誤,但不能走得更加進一步。 任何可以看到修復?

+0

什麼是'draw_title_ttf'?它從何而來?它沒有在課堂上聲明。 – Gasim

+0

是sdl-widgets lib的一個函數,它是sdl2 lib的一個包裝 –

回答

3

您確實需要使用[this][&]進行捕獲。我懷疑TopWinButton構造函數採用原始函數指針,而需要採取std::function

普通的香草函數指針與捕獲lambdas不兼容。 std::function能夠像一個函數指針一樣工作,該函數指針還允許安全存儲捕獲的數據。 (即當function對象本身被複制或銷燬時,捕獲的對象將需要被正確複製或銷燬)