可以使用继承来实现链表吗?
例如:
class List {/* ... */}; // abstract class
class IntList : public List {/* ... */}; // derived class
一种可能的解决方案是使List
基类仅处理节点,即跟踪列表头、尾和添加/删除节点。List
类可以有一个基本的Node
类,例如 IntList
专业化。
类似的东西
class List
{
public:
virtual ~List() {}
protected:
// Protected constructor so this class can only be inherited
List() {}
struct Node
{
Node* next;
Node* prev;
};
void add_head(Node*);
void add_tail(Node*);
Node* pop_head();
Node* pop_tail();
Node* get_head();
Node* get_tail();
private:
Node* head;
Node* tail;
};
class IntList : public List
{
public:
IntList();
~IntList();
void add_head(int); // Creates an `IntNode` and calls `add_head` with that
void add_tail(int); // Creates an `IntNode` and calls `add_tail` with that
int pop_head(); // Calls `pop_head` to get the node, and downcast to `IntNode`
int pop_tail(); // Calls `pop_tail` to get the node, and downcast to `IntNode`
int get_head(); // Calls `get_head` to get the node, and downcast to `IntNode`
int get_tail(); // Calls `get_tail` to get the node, and downcast to `IntNode`
private:
struct IntNode : List::Node
{
int value;
};
};