这个问题在这里已经有了答案:
Why can't variables be declared in a switch statement?
(23 个回答)
3年前关闭。
我不明白为什么我收到错误:
有人可以向我解释一下吗?
void LinkedList::process_example(int choice) {
switch(choice) {
case 1:
cout << endl << endl << "Current S = ";
this->printSet();
cout << "Enter an element :";
char* element = "lol";
//cin>>element;
cin.clear();
cin.ignore(200, '\n');
this->Addelementfromback(element); //error is here
cout << endl << endl << "Current S = ";
this->printSet();
break;
case 2:
this->check_element();
break;
case 3:
cout << endl << endl;
cout << "Current Set S = ";
this->printSet();
cout << endl << "S has ";
int count = this ->check_cardinality();
cout << count << " elements";
break;
}
}
最佳答案
尝试用 case
包裹 {}
,并将所有语句放入 {}
。
case 1:
{
cout << endl << endl << "Current S = ";
this->printSet();
// and other mess
}
break;
你应该把所有这些语句都放在函数中,保持
case
语句清晰。例如,编写这种样式:case 1:
initializeElement();
break;
case 2:
doSomethingElse();
break;
见 link
关于c++ - 'element' 的初始化被 'case' 标签跳过,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14669457/