C++ 错误C2361:初始化';发现';被'跳过;默认值';标签
可能重复:C++ 错误C2361:初始化';发现';被'跳过;默认值';标签,c++,compiler-errors,switch-statement,C++,Compiler Errors,Switch Statement,可能重复: 我在下面的代码中有一个奇怪的错误: char choice=Getchar(); switch(choice) { case 's': cout<<" display tree "; thetree->displaytree(); break; case 'i': cout<<" enter value to insert "<<endl; cin>>value; thetre
我在下面的代码中有一个奇怪的错误:
char choice=Getchar();
switch(choice)
{
case 's':
cout<<" display tree ";
thetree->displaytree();
break;
case 'i':
cout<<" enter value to insert "<<endl;
cin>>value;
thetree->insert(value);
break;
case 'f' :
cout<< "enter value to find ";
cin>>value;
int found=thetree->find(value);
if(found!=-1)
cout<<" found = "<<value<<endl;
else
cout<< " not found " <<value <<endl;
break;
default:
cout <<" invalid entry "<<endl;;
}
我认为我已经正确地编写了break和default语句,那么错误在哪里呢?您需要在花括号内声明
开关的大小写的内部变量。i、 e
case 'f' :
{
...
int found=thetree->find(value);
...
}
您需要用范围大括号括起您的案例“f”:
:
case 'f' :
{
cout<< "enter value to find ";
cin>>value;
int found=thetree->find(value);
if(found!=-1)
cout<<" found = "<<value<<endl;
else
cout<< " not found " <<value <<endl;
break;
}
案例“f”:
{
cout>值;
int found=树->查找(值);
如果(找到!=-1)
cout开关
的语义是转到
的语义:大小写
的语义不是
引入一个新的作用域。因此,在您的默认值:
案例中可以访问found
(虽然你实际上并没有访问它)。跳过一个不平凡的
初始化是非法的,因此您的代码是非法的
鉴于案例“f”:
的复杂性,最好的解决方案可能是
把它分解成一个单独的函数。如果不行,你可以
在{…}
中创建一个单独的作用域,或放弃
初始化、写入:
int found;
found = thetree->find(value);
(我提到这一点是为了完整性。这不是我想要的解决方案
建议。)如果您已经知道问题的答案,则这只是一个精确的副本。“默认”标签跳过了神秘的“错误C2361:found”的初始化不一定会让你产生一个问题:为什么变量不能在一个转换语句中声明?“我今天得到了同样的问题:”我不是C++专业人员,我不知道在没有“花键”的情况下声明一个指针是不允许的。所以,只要想一想,如果你知道答案或解决方案,想分享它,那么请分享。,但不要在这里表现得像个聪明的驴子。@Constantin同意“聪明的驴子”这句话——但你指的是谁?:)投票赞成一个实际的解释。“case
s不要引入一个新的范围”-这句话解释了一切。
int found;
found = thetree->find(value);