程序中,用基类类型指针,可以生成一个连接不同派生类对象的动态链表,
即每个节点指针可以指向类层次中不同的派生类对象。
这种节点类型不相同的链表称为异质链表。
如:任务管理器,管理不同的进程
#include "dialog.h"
#include <QApplication>
#include <QLabel>
#include <QPushButton>
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();
}
菜鸟笔记