Objective-C 方法定义中分号的意义是什么?
当我在一个类中查看一些更晦涩的实现代码时,我有点困惑,我发现了几个看起来像这样的方法定义:
- (void)doSomething; {
// Something...
}
- (void)doSomethingWithSomething:(Something*)aSomething; {
// Something with aSomething...
}
这显然是一个将方法声明复制并粘贴到实现块中然后忽略的工件提供定义时从声明中删除分号。
混乱源于这样一个事实:这些方法定义不仅可以编译,而且可以完美执行。我看到它们并立即预期会出现编译错误,就像您尝试一些 C 疯狂操作时可能会遇到的情况一样:
void doSomething(); {
/* Something */
}
那么问题就变成了,“那个分号到底是做什么的?”看起来它完全没有做任何事情,在这种情况下,问题就变成了,“为什么编译器允许在该特定位置使用单个随机分号?”没有分号是正常的,有分号显然也可以,但是多了是编译错误吗?
I was slightly confused when, looking through some of the more obscure implementation code in one of my classes, I found several method definitions that looked like:
- (void)doSomething; {
// Something...
}
- (void)doSomethingWithSomething:(Something*)aSomething; {
// Something with aSomething...
}
This is clearly an artifact from copying and pasting the method declarations into the implementation block and then neglecting to remove the semicolons from the declaration when providing the definition.
The confusion stems from the fact that these method definitions not only compile, they also execute perfectly. I saw them and immediately expected compile errors, like what you might expect if you were to attempt some C craziness like:
void doSomething(); {
/* Something */
}
So then the question becomes, "What does that semicolon even do?" It seems like it does absolutely nothing, in which case the question becomes, "Why does the compiler allow a single random semicolon in that particular location?" No semicolons is normal, one is apparently also fine, but any more is a compile error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它没有任何作用。它只是在您将方法声明从标头复制/粘贴到实现文件中时为您提供帮助。您不必删除分号,因此可以节省几次按键操作。该分号是完全可选的。
It doesn't do anything. It's just to help you when you copy/paste you method declarations from your header into your implementation file. You don't have to delete the semicolon, so it saves you a couple of keystrokes. That semicolon is totally optional.