2014-03-13 54 views
0

我已经声明了一个包含另一个类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); 
} 
+0

什么是编译错误? – hrkz

回答

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>的成员函数,因此您现在可以自由使用其中的名称。

+2

不仅'AVLNode'可能不需要模板,而且它的模板参数使用相同的名称'KeyType'作为它的封闭类'AVL'的参数是一个错误:''KeyType'声明的阴影模板参数“。 – iavr

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;你有一个AVLINT节点