create an object in switch-case
i use visual studi 2008. (c++)
in my switch case a wanted to create an o开发者_如何转开发bject, 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' ....
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;
}
}
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.
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;
}
精彩评论