gpt4 book ai didi

c++ - 我们可以使用继承来实现链表吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:20:29 26 4
gpt4 key购买 nike

是否可以使用继承来实现链表?
例如:

 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;
};
};

关于c++ - 我们可以使用继承来实现链表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27056211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com