create an object in switch-case

北慕城南 提交于 2019-12-22 12:26:02

问题


i use visual studi 2008. (c++)

in my switch case a wanted to create an object, but i doens't work.

is it right, that i can't create an object in a switch case?

if that's right,whats the best way to work around it,

a new method that's creates that object?

edit the code:

switch (causwahl){
case '1':
cAccount *oAccount = new cAccount (ID);

case '2' ....

回答1:


I can't say for sure with such a vague question, but I'm guessing that you're doing something like this:

switch(foo)
{
case 1:
  MyObject bar;
  // ...
  break;

case 2:
  MyObject bar;
  // ...
  break;
}

This isn't allowed because each case statement has the same scope. You need to provide more scope if you want to use the same variable name:

switch(foo)
{
case 1:
  {
    MyObject bar;
    // ...
    break;
  }

case 2:
  {
    MyObject bar;
    // ...
    break;
  }
}



回答2:


I suggest avoiding switch-case because of this and other problems. You can allow variable definitions by extra curly braces, but that looks messy and causes two levels of indentation. Other problems are that you can only use integer/enum values for cases, that the break statement cannot be used to break from a loop outside the switch. Forgetting to break is also a very common programming mistake that cannot be detected by the compiler (because it is still valid code) and it leads to hard to debug bugs.

Personally I only use switch-case with enum values, and even then never with a default label. This has the benefit of getting me a compile warning (from GCC) if not all possible values of the enum are handled.

There is nothing wrong with if-elses.




回答3:


switch (choice)
    {
    case 1:
        {
            cout<<"\nBike object created********"<<endl;
            Bike B1(2,4,50);
            V=&B1;
            V->Display_Details();

            V->CallToll(persons);
           break;
      }

    case 2:
       {  
            cout<<"\n CAR object created********"<<endl;
            Car C1(4,8,50);
            V=&C1;
            V->Display_Details();
            V->CallToll(persons);

         break;

       }
     default:
           cout<<"You have entered an invalid choice...........Please Enter valid choice........"<<endl;


    }

  



来源:https://stackoverflow.com/questions/2351936/create-an-object-in-switch-case

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