首页 > 解决方案 > 不能从 switch 语句跳转到这个 case 标签——多态性

问题描述

我是 C++ 的新手。我从多态性开始。如果我在 switchcase c++ 中创建一个类对象,请告诉我:“不能从 switch 语句跳转到这个 case 标签”,但是当我在 switch 之前创建它并且稍后我调用一个方法时,一切都会正确。我在每个类中都有一个构造函数,这很麻烦,在开关内完成构造函数的参数。这是我在真实代码中所做的一个方案。

class superClase{
       virtual double func1(){
           //do something
       }
};
class firstClass:public superClase{
private:
        double var1, var2;
public:
        firstClass(double a, double b ){
           var1=a;
           var2=b;
        }
        double func1(){
           return (var1*var2);
        }
};

class secondClass:public superClase{
private:
        double var1, var2;
public:
        secondClass(double a, double b ){
           var1=a;
           var2=b;
        }
        double func1(){
           return (var1+var2);
        }
};

int main(){
        int menu=0;
        double val1=0,val2=0;
        cout<<"1.adding or 2.multiply"<<endl;
        cin>>menu;
        switch (menu)
            case 1:
                  cout<<"input val1";
                  cin>>val1;
                  cout<<"input val2";
                  cin>>val2;
                  secondClass op(val1,val2);//here is my trouble
                  cout<<op.func1();
                  break;
            case 2:
                  cout<<"input val1";
                  cin>>val1;
                  cout<<"input val2";
                  cin>>val2;
                  firstClass op(val1,val2);//here is my trouble
                  cout<<op.func1();
                  break;
            default:
                  break;
            }
};

我的疑问是:

标签: c++switch-statementpolymorphism

解决方案


推荐阅读