2015-07-11 38 views
1

所以,我有我的課:C++如何訪問私有成員在類的std :: for_each的內部

class base 
{ 
public: 
    base (int member) : m_member(member) {}; 
    ~base() {}; 

    void func(void) 
    { 
    std::for_each(something.begin(), something.end(), [](OtherClass& myOtherClass) 
    { 
     GLfloat* stuff = myOtherClass.GetStuff(); 
     m_member = 1; //How can I access the private member here? 
    }); 
    }; 
private: 
    int m_member; 
} 

我得到這樣的警告:

'm_member' requires the compiler to capture 'this' but the current default capture mode does not allow it 

而這個錯誤:

'm_member' undeclared identifier 

如何訪問foreach中的私有成員m_member?

+2

您可以通過'this'作爲參數傳遞給拉姆達。 –

回答

2

在lambda之前的括號中,您可以捕獲函數體所需的符號。在這種情況下,你需要捕獲this,因爲你使用它的成員:

[this](OtherClass& myOtherClass) 
    { 
     GLfloat* stuff = myOtherClass.GetStuff(); 
     m_member = 1; 
    }); 

又見cpp reference約lambda表達式:

capture-list - comma-separated list of zero or more captures, optionally beginning with a capture-default. Capture list can be passed as follows (see below for the detailed description):

[a,&b] where a is captured by value and b is captured by reference.

[this] captures the this pointer by value

[&] captures all automatic variables odr-used in the body of the lambda by reference

[=] captures all automatic variables odr-used in the body of the lambda by value

[] captures nothing

+0

太棒了!謝謝! – waas1919

+0

當然:)我需要等10分鐘才能做到這一點;) – waas1919

+1

哦,我不知道這個限制存在! –