基于模板参数返回值

时间:2014-03-13 14:32:26

标签: c++

我已经声明了一个包含另一个类AVLNode的类AVL。 AVL类包含插入函数。我想插入返回AVLNode指针。我在这段代码中遇到编译错误。什么是错误?

template<class KeyType>
class AVL
{
    public:
        template<class KeyType>
        class AVLNode{};

        AVLNode<KeyType>* insert(const KeyType& key);
}

template<class KeyType>
AVLNode<KeyType>* AVL<KeyType>::insert(const KeyType& key)
{
    if (m_root == 0)
    {
        m_root = new AVLNode<KeyType>(key);
        return m_root;
    }
    else
        return insert_Helper(key,m_root);
}

2 个答案:

答案 0 :(得分:2)

您的AVLNode类模板是AVL中的嵌套类模板。要访问它,请使用AVL<KeyType>::AVLNode<KeyType>。 (我不确定为什么你让AVLNode成为一个类模板;我怀疑这是必要的。你真的想拥有AVL<int>::AVLNode<float>吗?)

或者,您可以使用尾随返回类型:

template<typename KeyType>
auto AVL<KeyType>::insert(const KeyType& key) -> AVLNode<KeyType>*

这是允许的,因为您已将此限定为AVL<KeyType>的成员函数,因此您现在可以自由使用其中的名称。

答案 1 :(得分:0)

@Anton_Golov说你的班级只需要一个模板,因为当你的节点可以浮动时,有一个整数树是没有意义的。您只需要一个模板。为了不与它们混淆,尝试让你的类更紧凑,保持整个函数在你的类中,我认为这是数据结构或某些开源应用程序的某种功课,所以没有必要写类之外的功能,因为你使用模板并且必须在类之外写很多东西。这是您的代码没有错误:

template<class KeyType>
class AVL
{
  public:
    class AVLNode{};
    AVLNode m_root;

    AVLNode* insert(const KeyType& key)
    {
        if (m_root == 0)
        {
            m_root = new AVLNode(key);
            return m_root;
        }
        else
            return insert_Helper(key,m_root);
    }
};

AVL<int> myTree;你有一个带有 int 节点的 AVL

相关问题