异质链表

本文介绍了一种使用基类指针连接不同派生类对象的动态链表——异质链表,并通过实例展示了其在任务管理器场景中的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

程序中,用基类类型指针,可以生成一个连接不同派生类对象的动态链表,

即每个节点指针可以指向类层次中不同的派生类对象。

这种节点类型不相同的链表称为异质链表。

如:任务管理器,管理不同的进程

 

 

#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();
}

 

转载于:https://www.cnblogs.com/xiangtingshen/p/11617574.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值