首页 > 解决方案 > 如何根据事件在 C++ 中初始化一个类?

问题描述

我的程序以用户提到的特定方式执行某些任务。完成这项任务的方法只有三种。问题在于,这三种方式虽然需要执行相同的工作,但需要使用不同的数据结构来实现特定位置的各种性能提升。因此,我为每种方式执行 3 个不同的课程。

我可以为每种方式编写一个单独的完整程序,但正如我之前提到的,它们执行的是相同的任务,因此会重复很多代码,感觉效率较低。

写这一切的最佳方式是什么?

我在想的是创建另一个类,比如这三个包含虚函数和所有类的“任务”基类。然后根据用户输入将其类型转换为三种方式之一。但是,我不确定我将如何做到这一点(从未做过任何接近此的事情)。

我找到了一个针对相同问题的答案- https://codereview.stackexchange.com/a/56380/214758,但仍然不清楚。我只想在那里问我的问题,但由于声誉点而不能这样做。

我的课程蓝图到底应该是什么样子?

编辑: 我期望的程序流程的伪代码:

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*/}

标签: c++inheritanceevent-handlingvirtual-functions

解决方案


我可以提出以下建议: 1) 阅读 C++ 中的多态性。2) 一般来说,请阅读 C++ 设计模式。但是对于您的情况,请阅读命令设计模式。

因此,不要使用强制转换,而是使用多态性:

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
}

当您拥有正确的对象时,您无需投射。我希望这有帮助。使用命令模式创建不同的命令,将它们放入队列中并执行它们......


推荐阅读