switch支路声明局部变量问题

switch支路声明局部变量问题

写魔兽2.0的时候发现了这种情况
在每个支路中,声明不同派生类指针,但是普通写法会有如下报错

Jump bypasses variable initialization

显示跳过了旁路的变量定义,应该是为了防止在该case未成立的情况下,在其他case调用这个变量
而在这个程序中,直到遇到switch的“}”右花括号,变量的作用域才终结
如果未经定义直接被调用就会出错
解决这个问题只需在每个case对应的代码加上“{}”限制作用域即可

 switch(Cir[cir]){
            case 0://dragon
            {Dragon * pDragon =  new Dragon(life[Cir[cir]], color, Cir[cir]);
                pDragon -> M(lifeR, this);
                pWarriors[time_h] = pDragon;}
                break;
            case 1://ninja
            {Ninja * pNinja =  new Ninja(life[Cir[cir]], color, Cir[cir]);
                pNinja-> M(lifeR, this);
                pWarriors[time_h] = pNinja;}
                break;
            case 2://iceman
            {Iceman * pIceman =  new Iceman(life[Cir[cir]], color, Cir[cir]);
                pIceman -> M(lifeR, this);
                pWarriors[time_h] = pIceman;}
                break;
            case 3://lion
            {Lion * pLion =  new Lion(life[Cir[cir]], color, Cir[cir]);
                pLion -> M(lifeR, this);
                pWarriors[time_h] = pLion;}
                break;
            default://wolf
            {Wolf * pWolf =  new Wolf(life[Cir[cir]], color, Cir[cir]);
                pWolf -> M(lifeR, this);
                pWarriors[time_h] = pWolf;}
        }

你可能感兴趣的:(一个bug,de一天,c++)