第十六课、顺序存储结构的抽象实现----------狄泰软件学院

一、课程目标

1、完成顺序存储结构的抽象实现,既然是抽象实现,自然就是抽象类,不能生成对象

(1)、抽象类模板,存储空间的位置和大小由子类完成 

(2)、这里只实现顺序存储结构的关键操作(增、删、查等)

(3)、提供数组操作符,方便快速获取元素(要提供const版本的,方便const对象调用)

二、具体实现

这里需注意几点

(1)、这里将capacity()函数设置为纯虚函数,说明在这里还不需要实现它,将其留到子类中在实现。

(2)、数组操作符的返回值一个是引用一个是值,是因为const对象不能修改线性表的内容,返回值不能作为左值,而非const对象可以

三、完整代码

#ifndef SEQLIST_H
#define SEQLIST_H
#include "List.h"
#include "Exception.h"

using namespace DTLib;

namespace DTLib
{

template <typename T>
class SeqList : public List<T>
{
private:
    T* m_array;
    int m_length;
public:
    bool insert(int i, const T& e)
    {
        bool ret = ((0 <= i) && (i <m_length));

        ret = ret && ((m_length + 1) <= capacity());

        if( ret )
        {
            for(int p=m_length-1; p>=i; p--)
            {
                m_array[p+1] = m_array[p];
            }

            m_array[i] = e;

            m_length++;
        }

        return ret;

    }

    bool remove(int i)
    {
        bool ret = ((0 <= i) && (i < m_length));

        if( ret )
        {
            for(int p=i; p<m_length-1; p++)
            {
                m_array[p] = m_array[p+1];
            }

            m_length--;
        }

        return ret;
    }

    bool set(int i, const T& e)
    {
        bool ret = ((0 <= i) && (i < m_length));

        if( ret )
        {
            m_array[i] = e;
        }

        return ret;
    }

    bool get(int i, T& e) const
    {
         bool ret = ((0 <= i) && (i < m_length));

         if( ret )
         {
             e = m_array[i];
         }

         return ret;
    }

    int length() const
    {

        return m_length;
    }

    void clear()
    {
        m_length = 0;
    }


    T& operator [] (int i)
    {
        if((0 <= i) && (i < m_length))
        {
            return m_array[i];
        }
        else
        {
            THROW_EXCEPTION(IndexOutOfBoundsException, "parameter i is invalid...");
        }
    }

    T operator [] (int i) const
    {
        return const_cast<SeqList<T>&>(*this)[i];//代码复用
    }

    virtual int capacity() const = 0;
};

}

#endif // SEQLIST_H
SeqList.h
原文地址:https://www.cnblogs.com/gui-lin/p/6833224.html