如何制作模板抽象类的列表

how to make a list of template abstract class

本文关键字:列表 抽象类 何制作      更新时间:2023-10-16

我必须做一个模板抽象基类的列表(我也有交付的类)但我不能将列表中的元素序列化,因为该元素是一个抽象类。。。

这是我的申报单:

/* fsm (list node) declaration */
template<class step_type> class fsm {
protected:
step_type   step;
step_type   step_old;
step_type   step_tmp;
char        name[256];
fsm *next;
fsm *prev;
public:
fsm(step_type step);
virtual void update() = 0;
void show(){cout << step << ' ' << step_tmp << 'n'; };
void init(step_type st_current) {step = st_current;};
//metodi per gestione nodo lista
step_type getStep()     { return step; }
fsm* getNext()          { return next; }
fsm* getPrev()          { return prev; }
void setStep(step_type s)   { step = s; }
void setNext(fsm *n)        { next = n; }
void setPrev(fsm *p)        { prev = p; }
};
/* fsm_List declaration */
template <class step_type>
class fsm_List
{
fsm<step_type> *head, *tail;
int size;
public:
fsm_List();
fsm<step_type>* getHead()    { return head; }
fsm<step_type>* getTail()    { return tail; }
int getSize()        { return size; }
void insert(fsm<step_type> *n);    // add node to list
void insert(step_type &value);        // new node and add in list
fsm<step_type> *search(step_type &value);    //first node with value
void delnode(fsm<step_type> *n);    // remove node
int delvalue(step_type &value);        // remove all nodes
};

这是我交付的课程:

class deri_pinza : public fsm<pin_steps>{
private:
bool    cmd_prelevamento_done;
public:
deri_pinza(): fsm<pin_steps>(ST_PIN_BOOT){
cmd_prelevamento_done = false;
};
void update();
};

其中:

enum pin_steps {
ST_PIN_BOOT,
ST_PIN_CHECK_MOTORE,
ST_PIN_ZERO_MOTORE,
ST_PIN_WAIT_ZERO_MOTORE,
ST_PIN_OPEN,
ST_PIN_READY,
};

我试着在我的主要测试,但它是错误的。。。

fsm<pin_steps> *one, *two, *three, *four, *five;
one = new fsm<pin_steps>(ST_PIN_CHECK_MOTORE);
two = new fsm<pin_steps>(ST_PIN_ZERO_MOTORE);
three = new fsm<pin_steps>(ST_PIN_WAIT_ZERO_MOTORE);
four = new fsm<pin_steps>(ST_PIN_OPEN);
five = new fsm<pin_steps>(ST_PIN_READY);

fsm_List<pin_steps> *mylist = new fsm_List<pin_steps>();
(*mylist)+=(*one);
(*mylist)+=(*two);

mylist->insert(one);
mylist->insert(two);

cout << *mylist << endl;

如何在不初始化fsm(抽象类)的情况下初始化List?

您不能使用new创建fsm<>的实例,因为它是抽象的-它包含纯虚拟方法virtual void update()=0;

例如:

fsm<pin_steps> *one...
one = new deri_pinza;

这是合法的,从这里开始。。。

编辑-我们评论的后续行动:

如果你需要一个更通用的deri-pinza(通用),它可以定义为:

template <typename STEP_TYPE>
class deri_pinza_gen : public fsm<STEP_TYPE> {
private:
bool cmd_prelevamento_done;
public:
deri_pinza_gen(STEP_TYPE step) : fsm<STEP_TYPE>(step){
cmd_prelevamento_done = false;
};
virtual void update();
virtual ~deri_pinza_gen();
};

然后:

mylist->insert( new deri_pinza_gen<pin_steps>(ST_PIN_BOOT) );
mylist->insert( new deri_pinza_gen<pin_steps>(ST_PIN_CHECK_MOTORE) );
ANOTHER_list->insert( new deri_pinza_gen<ANOTHER_pin_steps>(ANTHER_enum_item) );
...

是有效的插入。我已经在这里声明了update()是虚拟的,所以如果你需要的话,你可以从这个派生你的deri_pinza