Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 返回基于模板参数的值_C++ - Fatal编程技术网

C++ 返回基于模板参数的值

C++ 返回基于模板参数的值,c++,C++,我声明了一个类AVL,它包含另一个类AVLNode。 AVL类包含一个insert函数。我希望insert返回一个AVLNode指针。这段代码中有编译错误。怎么了 template<class KeyType> class AVL { public: template<class KeyType> class AVLNode{}; AVLNode<KeyType>* insert(const KeyTy

我声明了一个类AVL,它包含另一个类AVLNode。 AVL类包含一个insert函数。我希望insert返回一个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);
}
模板
类AVL
{
公众:
模板
类AVLNode{};
AVLNode*插入(常量键类型和键);
}
模板
AVLNode*AVL::插入(常量键类型和键)
{
如果(m_根==0)
{
m_root=新的AVLNode(键);
返回m_根;
}
其他的
返回insert\u Helper(key,m\u root);
}

您的
AVLNode
类模板是
AVL
中的嵌套类模板。要访问它,请使用
AVL::AVLNode
。(我不知道你为什么要制作
AVLNode
类模板;我怀疑这是必要的。你真的想拥有
AVL::AVLNode
?)

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

template<typename KeyType>
auto AVL<KeyType>::insert(const KeyType& key) -> AVLNode<KeyType>*
模板
自动AVL::insert(常量键类型和键)->AVLNode*

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

@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
{
公众:
类AVLNode{};
avlnodem_根;
AVLNode*插入(常量键类型和键)
{
如果(m_根==0)
{
m_root=新的AVLNode(键);
返回m_根;
}
其他的
返回insert\u Helper(key,m\u root);
}
};

使用
AVL-myTree
您得到了一个带有int节点的AVL

编译错误是什么?不仅是
AVLNode
可能不需要作为模板,但是,对其模板参数使用与其封闭类的参数相同的名称
KeyType
,这是一个错误:
对“KeyType”模板参数的声明。