提问人:user3674011 提问时间:10/7/2021 最后编辑:wohlstaduser3674011 更新时间:5/13/2022 访问量:235
C++ 闭包捕获变量
C++ closure capture variable
问:
在 Cow() 函数中。我正在尝试捕获闭合的可变重量。但它不能正常工作。可变重量不会捕获到瓶盖上。当我尝试运行getWeight()函数时。它返回一个未初始化的值。此外,setWeight() 不起作用。
#include <iostream>
struct Mammal {
std::function<void()> speak;
std::function<int()> getWeight;
std::function<void(int)> setWeight;
};
Mammal *Cow() {
int weight = 100;
auto *m = new Mammal();
m->speak = []() { puts("momo~~ momo~~"); };
m->getWeight = [&]() { return weight; };;
m->setWeight = [&](int w) { weight = w; };
return m;
}
int main() {
Mammal *c = Cow();
std::cout << "Cow Weight: " << c->getWeight() << '\n';
c->setWeight(200);
std::cout << "Cow New Weight: " << c->getWeight() << '\n';
}
答: 暂无答案
评论
weight
Mammal *Cow()
Mammal
std::function
weight