C++ 如何在 std::for_each 中访问 class 中的私有成员
C++ How to access private member in class inside std::for_each
所以我有我的 class:
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?
在 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
所以我有我的 class:
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?
在 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