此代码中的switch语句不起作用。它应该将(全局)变量x定义为A类的实例,如果用户按1则为B类,如果用户按2则定义为B类。如果用户按1则打印A,如果按2则打印B.我想要使用“x.print()”语句,其中x是A类或B类,具体取决于输入。
#include <iostream>
using namespace std;
class A{
public:
void print(){cout<<"A";}
};
class B{
public:
void print(){cout<<"B";}
};
int main() {
int choice;
cout<<"Press 1 to print A\nPress 2 to print B\n";
cin>>choice;
//I know the following does not work, it's just to show what I want to do
switch (choice){
case 1: A x;
break;
case 2: B x;
break;
}
x.print();
return 0;
}
答案 0 :(得分:1)
你没有详细说明实际上已经破坏了什么,但是从快速浏览你的代码开始,就会出现一系列问题:
x.print()
时不存在。x.print();
的含义。你必须确保这些类是相关的,要么通过从另一个派生出一个类,要么通过赋予两个类共同的祖先答案 1 :(得分:1)
试试这段代码。它使用多态来获得你想要的东西:
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() = 0;
};
class A : public Base{
public:
void print(){cout<<"A";}
};
class B : public Base{
public:
void print(){cout<<"B";}
};
int main() {
int choice;
cout<<"Press 1 to print A\nPress 2 to print B\n";
cin>>choice;
Base *x = NULL;
//I know the following does not work, it's just to show what I want to do
switch (choice){
case 1: x = new A();
break;
case 2: x = new B();
break;
}
x->print();
delete x;
return 0;
}
答案 2 :(得分:1)
您尝试做的似乎是根据条件创建类似的对象。为此,我建议继承。
class Base{
public:
virtual void print()=0;
};
class A : public Base{
public:
void print(){cout << "This is class A\n";}
}
所以主要看起来像:
Base* x = NULL;
switch (choice){
case 1: x = new A();
break;
case 2: x = new B();
break;
}
这就是你想要做的事情。
答案 3 :(得分:1)
您可以将答案修改为
#include <iostream>
using namespace std;
class super
{
public:
virtual void print() = 0;
};
class A: public super{
public:
void print(){cout<<"A";}
};
class B: public super{
public:
void print(){cout<<"B";}
};
int main() {
int choice;
cout<<"Press 1 to print A\nPress 2 to print B\n";
cin>>choice;
super* x;
switch (choice){
case 1: x = new A() ;
break;
case 2: x = new B();
break;
}
x->print();
return 0;
}
在这里,我们创建了一个由A类和B类实现的接口。然后使用运行时多态,我们创建了所需类的对象。