error: crosses initialization of ‘std::string xx变量‘

好久没写博客了,今儿就来水一篇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 dreaded goto labels; they do not constitute a new scope. Consequently, a switch selecting the correct case label to jump to is, for better or worse, a lot like goto 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之间,创建变量是不被允许的

解决方式有两种:

  1. 要么将两个 case 之间的语句写到一个新函数里,在新函数那个局部区域里,创建变量是随意的
  2. 要么用大括号将那个代码段括起来 , 对,就是这个大括号 {}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值