为什么这段代码会出现编译错误?
我试图理解闭包和函数指针之间的区别,我遇到了 这个SO 中的答案
我不明白的是这段代码
BOOL (*lessThanTest)(int);
int lessThan = 100;
lessThanTest = &LessThan;
BOOL LessThan(int i) {
return i < lessThan; // compile error - lessThan is not in scope
}
为什么考虑到 lessThan 是一个全局变量,可以从 LessThan 函数中访问它,为什么会出现编译错误,我错过了什么吗?
编辑
这不是我的代码,它取自SO 函数指针、闭包和 Lambda
I was trying to understand the difference between closures and function pointers, and I came across this answer in SO
What I don't understand is this code
BOOL (*lessThanTest)(int);
int lessThan = 100;
lessThanTest = &LessThan;
BOOL LessThan(int i) {
return i < lessThan; // compile error - lessThan is not in scope
}
Why there is a compile error consideringn that lessThan is a global variable, it can be accessed from within LessThan function, did I miss something?
EDIT
This is not my code, it's taken from an answer in SO Function pointers, Closures, and Lambda
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
闭包会带走其词法范围内的所有变量,从而可能延长它们的生命周期。函数指针则不然——如果代码中引用的变量消失了,它们就会被清除。
您给出的代码示例有点令人困惑。我相信它应该位于函数内部,这意味着
lessThan
是一个局部变量。如果退出该作用域,但函数指针仍然存在,则其代码将引用一个不存在的变量 -lessThan
。Closures take all the variables in their lexical scope along for the ride, possibly extending their lifetimes. Function pointers don't -- if the variables referenced inside their code disappear, they're hosed.
The code example you've given is a little bit confusing. I believe that it's meant to be inside of a function, meaning that
lessThan
is a local variable. If that scope is exited, but the function pointer still exists, then its code would have a reference to a non-existent variable --lessThan
.您错过了该答案中的一段话:
在您发布的内容中,
int lessThan
并不意味着在全局范围内,应该假设它位于某个函数中。You missed a paragraph in that answer:
In what you posted,
int lessThan
is not meant at global scope, it should be assumed to be in a function somewhere.好吧,不,如果
lessThan
是全局的,它不应该产生编译错误,尽管你很难通过这个片段来判断什么应该在哪里。例如,lessThanTest=&LessThan;
肯定来自某个本地范围。Well, no, if
lessThan
is global, it shouldn't produce compile error, though you can hardly tell by this fragment what is meant to be where.lessThanTest=&LessThan;
is definitely from some local scope, for instance.这段代码有一些问题:
lessThanTest
声明为未初始化的函数指针LessThan
。This code has some problems:
lessThanTest
as an uninitialized function pointerLessThan
before declaring it.