第一次博客難免有錯誤,歡迎大家批評指正,共同進步
其實容器類就是一個有各種容器的接口,通過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