gpt4 book ai didi

c++ - 使用模板和继承的容器实现

转载 作者:行者123 更新时间:2023-11-28 06:53:59 24 4
gpt4 key购买 nike

我正在尝试通过继承基本的 2-3 树容器来实现通用排名树容器

基本树声明如下:

    template<typename T>
class Node{
// etc..
}

template<typename T>
class Tree{
Node* root;
// etc
}

假设我想实现一个整数树,虽然我可以声明一个类如下:

class RankedNode : public Node<int>{

// ...
}

class RankedTree : public Tree<int>{
RankedNode root*; // for example

// ...
}

RankedNode 类将包含 Node 类的附加字段,这有助于快速遍历树 (O(log n)),并且通过使用继承,我将能够防止代码重复。

但是,我不知道如何正确地这样做,任何想法将不胜感激:)

最佳答案

您可以首先将Tree 设为N(节点类型)的模板,而不是T(值类型):

template<typename T>
class Node{
// etc..
}

template<typename N>
class Tree{
N* root;
// etc
}

这样写

class RankedNode : public Node<int>{

// ...
}

class RankedTree : public Tree<RankedNode>{
// RankedNode* root; <- remove this; it is already in Tree<RankedNode>

// ...
}

并且仅添加与基类相比真正新的字段。

关于c++ - 使用模板和继承的容器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23404193/

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