问题描述
是否可以在运行时选择派生类,然后执行具有不同参数编号/类型的方法?例如,我们有基类 Fruit
class Fruit{
public:
int weight;
Fruit(int);
};
Fruit::Fruit(int w) : weight(w){};
带有派生类 Apple
和 Orange
class Apple : public Fruit {
public:
void eat(int);
Apple(int);
};
Apple::Apple(int w) : Fruit(w){};
void Apple::eat(int amount){
weight -= amount;
};
class Orange : public Fruit {
public:
void eat(int,bool);
Orange(int);
};
Orange::Orange(int w) : Fruit(w){};
void Orange::eat(int amount,bool peel){
if (peel){
weight /= 10;
}
weight -= amount;
};
它们都有 eat
方法,但参数不同。如何选择在运行时创建哪个派生类然后执行 eat
?
int main(){
// read input i.e. (apple,5) or (orange,2,true)
// create either apple or orange
// eat it
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)