有几个子类的类的链表

Linked List of a class that has several subclasses?

本文关键字:链表 有几个 子类      更新时间:2023-10-16

所以我的问题是,我不知道一种方法来访问一个子类的字段只有一个指向基类的指针。我本来想问怎么做的,但我觉得对于链表有更好的解决方案。

所以如果你有一个父类parent和一个parent的链表,你可以使用dynamic_cast将它强制转换为子类,如下所示:

Child* child = dynamic_cast<Child*>(linkedlist_Parent_pointer);

你可以在这里找到更多关于dynamic_cast的信息:MSDN

链表伪代码示例:假设你有一个父类,比方说:P,然后你有a, B和C,它们继承自P,所以你可以有一个P的链表:

A* a;
B* b;
C* c;
P* p;
Node<P*>* linked_list(a);
Node<P*>* node2(b);
Node<P*>* node3(c);
Node<P*>* node4(p);
linked_list.InsertAfter(node2);
node2.InsertAfter(node3);
node3.InsertAfter(node4);
/*So, this way you have a linked list containing elements of type A, B, C, P, which are all of type P respectively.
If you want to get a value of a node, let's say, the value of the first node of the linked list:
*/
A* a_val = dynamic_cast<A*>(linked_list.val);

所有这些都考虑到一个节点类,如:

template<class T>
class Node
{
public:
Node(T* value)
{val = value;}
InsertAfter(Node<T>* node)
{next = node;}
T* val;
Node<T*>* next;
}

这只是一个简化的例子,希望能帮助你。

通常,基类具有enum类型,然后继承类填充该类型。

class base
{
  base() { t = TYPE_UNKNONW; }; 
  base (enum type) { t = TYPE_A; };
  enum  type { TYPE_UNKNONW, TYPE_A, TYPE_B };
  protected:
     enum type t;
}
class A : public base
{ 
    A (enum type x) : base (x) {};
}

那么在成员函数中,可以有一个switch语句。当dynamic_cast不可用时,这是另一种选择