程序中,用基类类型指针,可以生成一个连接不同派生类对象的动态链表,
即每个节点指针可以指向类层次中不同的派生类对象。
这种节点类型不相同的链表称为异质链表。
如:任务管理器,管理不同的进程
#include "dialog.h" #include#include #include class base { public: virtual void show() = 0; virtual ~base(){} }; class node { public: node *next; base *data; }; class yizhilinklist { public: yizhilinklist() { head = nullptr; } ~yizhilinklist() { if(head != nullptr) { delete head->data; head = head->next; } } node* add(base *base) { if (head == nullptr){ head = new node(); head->data = base; head->next = nullptr; } else { node *tmp = head; node *n = new node(); n->data = base; n->next = nullptr; while(tmp->next != nullptr) { tmp = tmp->next; } tmp->next = n; } return head; } void show() { while (head != nullptr) { head->data->show(); head = head->next; } } private: node *head; }; class mylable:public base { private: qlabel label; public: mylable(){ } ~mylable(){ } void show() { label.settext("this is label"); label.show(); } }; class mybutton:public base { private: qpushbutton button; public: mybutton(){ } ~mybutton(){ } void show() { button.settext("this is button"); button.show(); } }; class mydialog:public base { private: dialog w; public: mydialog(){ } ~mydialog(){ } void show() { w.show(); } }; int main(int argc, char *argv[]) { qapplication a(argc, argv); base *l = new mylable(); base *b = new mybutton(); base *d = new mydialog(); yizhilinklist yi; yi.add(l); yi.add(b); yi.add(d); yi.show(); return a.exec(); }