第一次博客难免有错误,欢迎大家批评指正,共同进步
其实容器类就是一个有各种容器的接口,通过C++继承与多态的特性,能够自由的往容器类中添加各种数据结构。上图就是这个容器类的基本结构。其中带箭头的线表示继承关系、带矩形的线表示组成关系、带圆形的线表示这个类是一个纯虚类(可以理解成接口)
为了编码的便捷,在下面的编码中我并没有自己写排序的算法,而是调用了algorithm 中的std::sort()函数.
Collection.hpp
// Created by BowenWu in 20160416
#ifndef Collection_hpp
#define Collection_hpp
class Collection {
protected:
typedef int E;
public:
virtual ~Collection() {}
// 并且加入空函数体, 因为对于析构函数来说
// 是不能定义为纯虚函数的
virtual void add(E e) = 0;
virtual void clear(void) = 0;
virtual bool contain(E e) = 0;
virtual bool isEmpty(void) = 0;
virtual void remove(E e) = 0;
virtual void sort(void) = 0;
virtual int size(void) = 0;
};
#endif // !Collection_hpp
在Collection 的构造过程中,一定要注意析构函数不能省略,并且声明为virtual,因为声明成了virtual而不是pure virtual,所以必须要给他一个函数的定义,这里就把他声明成空的就可以了。
如果不将析构函数写成virtual,或者省略,最后析构函数就不会具有多态的特性,导致ArrayList 或者其他的一些类的析构函数不会被调用,导致内存泄漏。(我就在这个地方卡了几个小时,血的教训:))
List.hpp
// Created by BowenWu in 20160416
// List.hpp--Abstract Class
#ifndef LIST_HPP
#define LIST_HPP
#include "Collection.hpp"
class List :public Collection{
public:
virtual ~List() {}
// 与Collection类似, 声明为virtual
virtual void add(E e) = 0;
virtual void clear(void) = 0;
virtual bool contain(E e) = 0;
virtual bool isEmpty(void) = 0;
virtual void remove(E e) = 0;
virtual E& operator[](int index) = 0;
virtual E& get(int index) = 0;
virtual int indexOf(int element) = 0;
virtual void sort(void) = 0;
virtual int size(void) = 0;
};
#endif // !LIST_HPP
两个纯虚类的构造就这样,下面就是ArrayList和LinkedList的具体实现,个人觉得这题最难的地方就是析构函数,因为自己因为这个卡了很久:)
ArrayList.hpp
#ifndef ARRAYLIST_H_
#define ARRAYLIST_H_
#include "List.hpp"
class ArrayList : public List {
public:
ArrayList();
~ArrayList();
virtual void add(E e);
virtual void clear(void);
virtual bool contain(E e);
virtual bool isEmpty(void);
virtual void remove(E e);
virtual E& operator[](int index);
virtual E& get(int index);
virtual int indexOf(E element);
virtual void sort(void);
virtual int size(void);
private:
E* storage;
int _size;
int _maxsize;
static const int extend_factor = 2;
void extend(void);
};
#endif
LinkedList.hpp
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include "List.hpp"
#include <iostream>
class LinkedList : virtual public List {
public:
typedef struct node {
E data;
struct node* next;
struct node* prev;
node(E data, struct node* next = NULL, struct node* prev = NULL)
: data(data), next(next), prev(prev) {}
} node;
LinkedList();
~LinkedList();
virtual void add(E e);
virtual void clear(void);
virtual bool contain(E e);
virtual bool isEmpty(void);
virtual void remove(E e);
virtual E& operator[](int index);
virtual E& get(int index);
virtual int indexOf(E element);
virtual void sort(void);
virtual int size(void);
private:
node* head;
node* tail;
int _size;
};
#endif