所以我的问题是,我不知道有什么方法可以仅通过指向基类的指针来访问子类的字段。我本来想问问怎么做,但我认为链表可能有更好的解决方案。
最佳答案
因此,如果您有一个像 Parent 这样的父类和一个 Parents 链表,您可以使用 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;
}
这只是一个简化的例子,希望对您有所帮助。
关于c++ - 具有多个子类的类的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23698493/