初始化块和指定范围的块之间有区别吗
如果您编写一个类并使用类似的内容,
...
int x;
{ x = 2; }
...
这将是一个初始化块,对吧?
那么如何使用花括号来指定范围,以便它们像任何其他代码一样执行?基本上,它们不是构造函数的一部分。
例如,
如果您要在 switch 语句中使用块,它会像初始化块一样执行吗?
switch(...)
{
case :
{ // this right here how does the compiler know the difference?
...
break;
}
}
If you writing a class and you use something like this
...
int x;
{ x = 2; }
...
This would be an initialisation block right?
So how would you use curly braces just to designate scope, so that they are executed like any other code? Basically so they are not part of the constructor.
Ex
if you were to use a block inside a switch statement, would this be executed like an initialisation block?
switch(...)
{
case :
{ // this right here how does the compiler know the difference?
...
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
初始化块仅适用于类范围内且前面没有函数原型的块(即不是函数体的块)。
在函数体内,您创建的任何块都会引入作用域,但不会被解释为初始化。
例子:
Initialization blocks only apply to blocks that are in the scope of a class and are not preceded by a function prototype (i.e. blocks that are not the body of a function).
Within the body of a function, any blocks that you create will introduce scope but will not be interpreted as an initialization.
Example: