Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c++ - Choose derived class at runtime and run unique class method

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use approach similar to command pattern. Pass different parameters through the constructor and execute different implementation of eat method when needed. Like this:

class Fruit {
  public:
  int weight;
  Fruit(int);
  virtual void eat() = 0;
};

Fruit::Fruit(int w) : weight(w){};

class Apple : public Fruit {
  public:
  void eat() override;
  Apple(int, int);
  int amount;
};

Apple::Apple(int w, int a) : Fruit(w){};

void Apple::eat() { weight -= amount; };

class Orange : public Fruit {
  public:
  void eat() override;
  Orange(int, int, bool);
  int amount;
  bool peel;
};

Orange::Orange(int w, int a, bool p) : Fruit(w), amount{a}, peel{p} {};

void Orange::eat() {
  if (peel) {
    weight /= 10;
  }
  weight -= amount;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...