【发布时间】:2021-03-18 15:51:14
【问题描述】:
我不知道我需要多少同一个类实例的成员变量 varX。 varX 具有相同的数据类型。在 .hpp 中声明它们是不可能的
// A.hpp
Class A
{
private:
T var1;
T var2;
T var3;
void some_method_using_varX();
...
}
// A.cpp
void A::some_method_using_varX()
{
this->varX = this->someMethod([this]() //varX has to be from the same class instance "this"
{
this->varX->otherMethod(); //I also need to access varX inside lambda
});
}
编辑:
问题是我没有目的跟踪向量中的索引。如何确保在 lamda 函数中访问正确的元素?
void A::some_method_using_var()
{
this->vars.push_back(var);
this ->vars.back() = this->someMethod([this]()
{
//when the lambda access the var it may not be the same var
//as some_method_using_var() could be called
//before the previous lambda finishes
this->vars.back()->otherMethod();
});
}
【问题讨论】:
-
使用
std::vector? -
std::vector可能是你想要的。 -
请注意,虽然
vector可能是您想要的(提供的细节很少),但它并不是一个适合所有建议的尺寸。例如,vector不能保存 const 值。