简体   繁体   中英

How to initialize a class in c++ based on an event?

My program performs some task in a specific manner mentioned by the user. There are exactly three ways to do the task. The problem is that the three ways, although doing the same job are needed to be implemented using different data structures for various performance boosts at specific places. So, I am performing 3 different classes for each way.

I could write a separate complete procedure for each way, but as I mentioned earlier, they are performing the same task, and so a lot of code repeats, which feels less effective.

What is the best way to write all this?

What I am thinking is of creating another class, say 'Task' base class of these 3 classes containing virtual functions and all. And then according to the user input typecast it to one of the three ways. But, I am not sure how am I going to do this (never did anything close to this).

I found an answer focusing on somewhat same issue- https://codereview.stackexchange.com/a/56380/214758 , but am still not clear with it. I wanted to ask my problem there only, but can't do because of reputation points.

How exactly my blueprint of classes should look like?

EDIT: PseudoCode for program flow I expect:

class method{......}; //nothing defined just virtual methods
class method1: public method{......};
class method2: public method{......};
class methods: public method{......};

main{/*initialise method object with any of the child class based on user*/
/*run the general function declared in class method and defined in respective class method1/2/3 to perform the task*/}

I can propose the following: 1) Read about polymorphism in c++. 2) In general, read about c++ design patterns. But for your case, read about Command design pattern.

So, Instead of casting, use polymorphism:

class Animal
{
  virtual void sound() = 0; // abstract
};

class Cat : public Animal
{  
  virtual void sound(){ printf("Meouuw") }
};

class Dog : public Animal
{
  virtual void sound(){ printf("Bauuu") }
};

int main()
{
  Animal *pAnimal1 = new Cat(); // pay attention, we have pointer to the base class!
  Animal *pAnimal2 = new Dog(); // but we create objects of the child classes

  pAnimal1->sound(); // Meouuw
  pAnimal2->sound(); // Bauuu
}

You don`t need to cast, when you have the right objects. I hope this helps. Use command pattern to create different commands, put them eg in a queue and execute them...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM