有几个子类的类的链表
Linked List of a class that has several subclasses?
所以我的问题是,我不知道一种方法来访问一个子类的字段只有一个指向基类的指针。我本来想问怎么做的,但我觉得对于链表有更好的解决方案。
所以如果你有一个父类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不可用时,这是另一种选择
相关文章:
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- 我对数据结构、双向链表有一些问题
- 为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?
- 我有几个关于参考变量的问题
- 分段错误,同时减去链表的 2 个连续节点
- 两次删除链表有什么区别?
- 这是在双链表的第一个节点之后插入节点的正确方法吗?
- C 读取大文件,其中有几个部分
- 从链表的第一个节点中删除时出现段错误
- 链表的几种实现 - C++
- 使用链表添加两个数字
- 我是C++新手,我有几个问题想问
- 这个计数链表有什么问题
- 在循环双向链表的第一个节点之前/之后插入的算法是什么?
- 如何在 c++ 中删除链表的第一个节点
- 链表-插入多个节点
- c++中虚方法表的几个问题
- 如果我有几个重叠的QTimer,会发生什么
- 用链表在多个函数中使用文件
- 为什么将链表的第一个节点声明为指针