为什么我不能实例化开关盒内的对象 [英] why i cant instantiate objects inside a switch-case block

查看:140
本文介绍了为什么我不能实例化开关盒内的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有3个类n_hexa,n_octa,n_bin。代码在这里

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;
}

在编译时会显示一条消息 crosses initialisation of n_hexa 对于n_octa的行

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

推荐答案

如果你想在一个case中有临时对象,正确。

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;
    }
}

这篇关于为什么我不能实例化开关盒内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆