我想实现用C++这块高阶功能的蟒蛇:不同的结果C++ 14
def add1(x):
def helper():
nonlocal x
x += 1
return x
return helper
这里有三个版本我创建:
#include <iostream>
#include <functional>
using namespace std;
function<int(void)> add1_v1(int x) {
function<int(void)> g = [&x]() {return ++x;};
return g;
}
auto add1_v2(int x) {
function<int(void)> g = [&x]() {return ++x;};
return g;
}
auto add1_v3(int x) {
auto g = [&x]() {return ++x;};
return g;
}
int main() {
auto a = add1_v1(100);
auto b = add1_v2(100);
auto c = add1_v3(100);
for(int i = 0; i < 3; ++i) {
cout << a() << endl;
}
cout << "-------------------------------------------" << endl;
for(int i = 0; i < 3; ++i) {
cout << b() << endl;
}
cout << "-------------------------------------------" << endl;
for(int i = 0; i < 3; ++i) {
cout << c() << endl;
}
return 0;
}
输出为:
101
102
103
-------------------------------------------
4239465
4239466
4239467
-------------------------------------------
4201325
4201325
4201325
只有add1_v1匹配我想要的东西。任何人都可以解释我的理由吗?
什么是“不工作”是什么意思? – Brian
@Brian修改了这个问题。 –
他们都错了。 'add1_v1'很幸运。 – immibis