why i cant instantiate objects inside a switch-case block

好久不见. 提交于 2020-01-12 15:54:53

问题


my code has 3 classes n_hexa,n_octa,n_bin. The code is here

switch(choice)
{
case 1: cin>>n; 
 n_hexa nx(n);
        break;
case 2: cin>>n; 
 n_octa no(n);
        break;
case 3: cin>>n;
 n_bin nb(n);
        break;
}

on compiling it gives a message "crosses initialisation of n_hexa" for line of n_octa


回答1:


If you want to have temporary objects inside a case, you'll need to scope them properly.

switch(choice)
{
    case 1:
    {
         cin>>n; 
         n_hexa nx(n);
         break;
    }
    case 2:
    {
         cin>>n; 
         n_octa no(n);
         break;
    }
    case 3:
    {
         cin>>n;
         n_bin nb(n);
         break;
    }
}



回答2:


Try declaring the variables above the switch command:

n_hexa nx;
n_octa no;
n_bin nb;
switch(choice) {
    case 1:
        cin>>n;
        nx(n);
        break;
...



回答3:


Ebomike's post has the answer to get rid of the errors. Now the reason is,

From Standard docs 6.7.3,

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps77) from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has trivial type (3.9) and is declared without an initializer (8.5).

An example from the Standard docs itself,

void f()
{
// ...
goto lx; // ill-formed: jump into scope of a
// ...
ly:
X a = 1;
// ...
lx:
goto ly; // OK, jump implies destructor
// call for a followed by construction
// again immediately following label ly
}

In which the statement goto lx; is ill-formed because it is being jumped to the statement lx, where the scope of a is visible.

Also,

77)The transfer from the condition of a switch statement to a case label is considered a jump in this respect.

So, this applies to switch as well.

And if braces {} are put in them, the scope is limited to the braces and you are free to declare within each case statement.

Hope that helps..



来源:https://stackoverflow.com/questions/4395289/why-i-cant-instantiate-objects-inside-a-switch-case-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!