在开关中声明类对象,然后在开关外使用该变量 [英] declaring class objects in a switch and later using that variable outside the switch
问题描述
有没有一种方法可以解决这个问题?我在switch语句中声明类对象,然后在switch外使用该变量,只有在每种情况下我都将其余代码都放在那儿时才有效,这才有效.代码
Is there a way to work around this?Im declaring class objects in a switch statement and later using that variable outside the switch, it only works if i put the rest of my code in each case which isnt very efficient.Heres my code
switch (shape)
{
case 'q':
{
Quad geo(a,b,c,d);
}
break;
case 'r':
{
Rectangle geo(a,b,c,d);
}
break;
case 't':
{
Trapezoid geo(a,b,c,d);
}
break;
case 'p':
{
Parrelogram geo(a,b,c,d);
}
break;
case 's':
{
Square geo(a,b,c,d);
}
break;
default:
break;
}
geo.print();//obviously wont work
推荐答案
具有这样的IPrintable
接口
struct IPrintable
{
virtual ~IPrintable() {}
virtual void Print() = 0;
};
然后,从IPrintable
派生您的类型Quad
,Rectangle
等,即实现该接口.然后您的代码如下:
Then, derive your types Quad
, Rectangle
, etc from IPrintable
, i.e. implement that interface. Then your code looks like this:
std::unique_ptr<IPrintable> pShape;
switch(shape)
{
case quad:
pShape.reset(new Quad(...));
case rect
pShape.reset(new Rect(...));
}
if(pShape)
pShape->Print();
当然,如果常用功能不只是打印功能,还可以将这些功能添加到界面中.还要看看访客模式.根据您问题的具体情况,它可能对您有帮助也可能没有帮助.
Of course, if the common functionality is more than print, you can add those functions to the interface as well. Also take a look at the visitor pattern. It may or may not be of help to you depending on the specifics of your problem.
这篇关于在开关中声明类对象,然后在开关外使用该变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!