変数の初期化は「case」タグによってスキップされます



Variable Initialization Is Skipped Bycasetag



問題:

機器管理システムを作成するとき、スイッチケースを使用して選択範囲を作成するときに、小さな問題が見つかりました。変数がケースの直下で初期化されると、エラーが報告されます。「「temp」の初期化は「case」ラベルによってスキップされます。」
例えば

switch(cho3) { case 1: department temp//Create a new department //******Create a new object here, the result is directly skipped by the case, making the program report an error cout<<'Please enter the department number:' cin>>temp.denum while (myinstrument.de_search2(temp.denum)) { cout<<'Department ID is duplicated!~~~~(>_<)~~~~!'<<endl cin>>temp.denum } cin.clear() cin.sync() cout<<'Department name:' cin>>temp.name cout<<'Department Number:' cin>>temp.denum myinstrument.Adddepartment(temp)//Save all the above department information myinstrument.Save2()//Write information to the document cout<<'Information saved successfully'<<endl break

解決:

方法1:ケースの後で変数を初期化する場合は、これらのステートメントを{}で囲む必要があります。

方法2:switch-case構造の外部で変数を初期化する