Is it possible to choose a derived class at runtime and then execute a method which has different argument number/types? Example, we have base class Fruit
class Fruit{
public:
int weight;
Fruit(int);
};
Fruit::Fruit(int w) : weight(w){};
with derived classes Apple
and 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;
};
They both have the method eat
but with differing arguments. How can I choose which derived class to create at runtime and then execute eat
?
int main(){
// read input i.e. (apple, 5) or (orange, 2, true)
// create either apple or orange
// eat it
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…