好久没写博客了,今儿就来水一篇hhh
学C++之前不是要先复习下C嘛,然后就从网上随便找了个项目敲一敲
我就不放源码了,大家应该都懂的,很简单的那种项目hhh
case 4:
cout << "请输入查找的名字" << endl;
string new_name;
cin >> new_name;
break;
case 0: // <-----报错
break;
default: // <-----报错
break;
然后,此段代码报错了
F:\C++\txl\main.cpp:105: error: crosses initialization of 'std::string new_name'
string new_name;
^
于是,我将那个从新定义字符串的代码扔到了`switch`外面,没再报错了,但我还是不知道这是为啥,google一下后
参考了之后:
https://stackoverflow.com/questions/42608101/crosses-initialization-of-string-and-jump-to-label-case
大佬的意思是
case
labels are really a lot like dreadedgoto
labels; they do not constitute a new scope. Consequently, aswitch
selecting the correctcase
label to jump to is, for better or worse, a lot likegoto
statement jumping to a label. The jump is not allowed to cross the initialisation of your various objects - exactly as the error messages say.
简单说一下就是,switch
就是像是 goto
语句,他不会创建一个新scope(这个怎么翻译?大概是域的意思?),在由goto关键词到label之间,创建变量是不被允许的
解决方式有两种:
- 要么将两个
case
之间的语句写到一个新函数里,在新函数那个局部区域里,创建变量是随意的 - 要么用大括号将那个代码段括起来 , 对,就是这个大括号
{}