switch中定义临时变量报错
(1) 错误代码
图 1 错误代码
(2) error:crosses initialization of
(3) 错误原因:The scope of a variable extends from the point where it is defined to the first closing brace that matches the closest opening brace before before the variable was defined.
(4) 翻译:变量的范围从定义该变量的点扩展到定义该变量之前与最近的左大括号匹配的第一个右大括号。
(5) 个人理解:也就是说,定义在分支中的临时变量生命周期是整个switch模块,也就是说在没有触发StationEditorNode条件时default 可以访问StationEditorNode分支中定义的变量。但这个时候并没有被定义。
(6) 解决方案,改变对应作用域即可
① 方案一
图 2 方案一
② 方案二
图 3 方案二
方案一中当StationEditorNode分支结束之后对应的临时变量生命周期结束。
方案二中变量生命周期是对应函数体的生命周期。