在开关中声明类对象,然后在开关外部使用该变量
有没有办法解决这个问题?我在 switch 语句中声明类对象,然后在 switch 之外使用该变量,只有当我将其余代码放在每种情况下时才有效,这不是很有效。这是我的代码
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个
IPrintable
接口,如下所示然后,从
IPrintable
派生您的类型Quad
、Rectangle
等,即实现那个界面。那么你的代码看起来像这样:当然,如果常用功能不仅仅是打印,你也可以将这些功能添加到界面中。还要看看访客模式。它可能对您有帮助,也可能没有帮助,具体取决于您问题的具体情况。
Have an
IPrintable
interface, like thisThen, derive your types
Quad
,Rectangle
, etc fromIPrintable
, i.e. implement that interface. Then your code looks like this: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.
不,这是不可能的。
geo
在编译时只能有一种类型,并且在运行时不能改变。您可以使用动态分配和多态性做类似的事情,但这可能不是解决您的问题的最佳解决方案。
知道 Quad 是其他类的基类后,以下可能是一个可用的解决方案:
该解决方案不是特别漂亮,主要是因为它使用原始指针以及
new
和delete 直接。更精致的版本将使用工厂模式,返回智能指针。
No, it is not possible.
geo
can only have one type at compile time, and it cannot change at runtime.You could do something similar with dynamic allocation and polymorphism, but it might not be the best solution to your problem.
With the knowledge that Quad is the base class of the others, the following might be a usable solution:
This solution is not particularly pretty, mainly because it uses raw pointers and
new
anddelete
directly. A more polished version would use theFactory
pattern, returning a smart pointer.