joh*_*ith 7 c++ nested function
我之前尝试过询问,但我不是很清楚,所以我重新询问它.
我想要一个取决于另一个变量值的变量,例如本例中的b:
int main(){
int a;
dependent int b=a+1; //I'm just making this up
a=3;
cout << b; //prints 4
a=4;
cout << b; //prints 5
}
Run Code Online (Sandbox Code Playgroud)
当然,这在C++中不存在,但这正是我想要的.
所以我试着做一个函数:
int main(){
int a;
int b(){ return a+1; } //error
a=3;
cout << b(); //would print 4 if C++ allowed nested functions
a=4;
cout << b(); //would print 5 if C++ allowed nested functions
}
Run Code Online (Sandbox Code Playgroud)
上述方法不起作用,因为C++不允许嵌套函数.
我只能在main()之外创建函数,如下所示:
int b(){
return a+1; //doesn't work because a is not in scope
}
int main(){
int a;
a=3;
cout << b();
a=4;
cout << b();
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为a与b()的范围不同,所以我必须传递一个参数,我不想这样做.
是否有任何技巧可以获得类似于在C++中工作的因变量?
你需要的是一个封闭.如果你可以使用C++ 0x功能,那么你很幸运.否则,您可以手动定义一个:
#include <iostream>
using namespace std;
struct B
{
const int & a;
B(const int & a) : a(a) {}
// variable syntax (Sean Farell's idea)
operator int () const { return a + 1; }
// function syntax
int operator () () const { return a + 1; }
};
int main()
{
int a;
B b(a);
a = 3;
cout << b << '\n'; // variable syntax
a = 4;
cout << b() << '\n'; // function syntax
}
Run Code Online (Sandbox Code Playgroud)
你也可以B
在里面定义main
,但有些编译器不喜欢它.
在的C++ 0x拉姆达语法如下:
auto b = [&]() { return a + 1; }
Run Code Online (Sandbox Code Playgroud)
这[&]
意味着lambda通过引用捕获局部变量.
如果您使用的是C++ 0x(GCC 4.5 +,Visual C++ 2010),则可以使用lambdas:
int a = 5;
auto b = [&a]{ return a + 1; };
std::cout << b() << std::endl;
Run Code Online (Sandbox Code Playgroud)
但是,根据你正在做的事情,可能有更清晰的解决方案 - 可能是一些经典"方法的变体,它接受'a'并返回'b'"