【发布时间】:2021-04-14 12:36:40
【问题描述】:
是否可以在运行时选择派生类,然后执行具有不同参数编号/类型的方法?例如,我们有基类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
}
【问题讨论】:
-
好吧,你可以使用类似命令模式的东西。使用构造函数作为参数,然后在虚函数中执行您的操作。
-
如果你输入
(orange, 5)会发生什么?
标签: c++ oop derived-class variant