如何将列表类转换为模板,使其能够处理任何数据

How to convert list class to template so that it work with any data?

本文关键字:处理 数据 任何 列表 转换      更新时间:2023-10-16

如何将列表类转换为模板链接类,使其能够处理任何数据。下面是一个使用整数的类。我想把它转换成模板类,这样它就可以与任何数据类型的一起工作

#ifndef _INTLIST_H_
#define _INTLIST_H_
#include <iostream>
class IntListNode
{
    protected:
        int value;
    public:
        IntListNode* nxt;
        IntListNode(int = 0, IntListNode* = NULL);
        IntListNode(const IntListNode&);
        IntListNode& operator=(const IntListNode&);
        int val() const;
        void val(int);
        IntListNode* next() const;
};
class IntList
{
    protected:
        IntListNode* nhead;
        IntListNode* tail;
        int csize;
    public:
        IntList();
        IntList(const IntList&);
        IntList& operator=(const IntList&);
        int size() const;
        IntListNode* head() const;
        void push(int);
        void pop();
        void clear();
        ~IntList();
};
#endif

这就是我所做的

#ifndef _INTLIST_H_
#define _INTLIST_H_
#include <iostream>
template <class T>
class IntListNode
{
    protected:
        T value;
    public:
        IntListNode* nxt;
        IntListNode(int = 0, IntListNode* = NULL);
        IntListNode(const IntListNode&);
        IntListNode& operator=(const IntListNode&);
        T val() const;
        void val(T);
        IntListNode* next() const;
};

template <class T>
class IntList
{
    protected:
        IntListNode<T> nhead;
        IntListNode<T>tail;
        int csize;
    public:
        IntList();
        IntList(const IntList&);
        IntList& operator=(const IntList&);
        int size() const;
        IntListNode* head() const;
        void push(T);
        void pop();
        void clear();
        ~IntList();
};
#endif
  1. IntLisNode更改为ListNode,并使其成为类模板
  2. IntLis更改为List,并使其成为类模板。在List中使用ListNode<T>而不是IntListNode
  3. 在某些地方用T代替int,在函数签名中用T const&代替

这是一个快速的改造。

#ifndef _LIST_H_
#define _LIST_H_
#include <iostream>
template <typename T>
class ListNode
{
    protected:
        T value;
    public:
        ListNode* nxt;
        ListNode(T const& in, ListNode* = NULL);
        ListNode(const ListNode&);
        ListNode& operator=(const ListNode&);
        T const& val() const;
        void val(T const&);
        ListNode* next() const;
};
template <typename T>
class List
{
    protected:
        ListNode<T>* nhead;
        ListNode<T>* tail;
        int csize;
    public:
        List();
        List(const List&);
        List& operator=(const List&);
        int size() const;
        ListNode<T>* head() const;
        void push(T const& val);
        void pop();
        void clear();
        ~List();
};