递归调用模板 class 的成员函数

Calling member function of a template class recursively

我有一个 avltree 作为模板的工作实现 class。我正在向这个工作实现中添加两个函数。这两个函数将递归地遍历整个树并执行一些计算。

//avltree.cpp
//see comment in code below

template <class Comparable>
void AvlTree<Comparable>::transverseTree( AvlNode<Comparable> *t, const char *word, char matchingWords[100][MAX_LENGTH + 1], int *count) const
{

    int distance;

    if( t != NULL )
    {
        distance = levDistance(t->element/*avl word*/, word);
        if (distance == 1)
        {
            *count++;
            strcpy(matchingWords[*count], t->element/*avl word*/);
        }

        //error is here
        transverseTree( t->left, word, matchingWords );
        transverseTree( t->right, word, matchingWords );
    }
}

//avltree.h

//new function
void transverseTree(AvlNode<Comparable> *t, const char *word, char matchingWords[100][MAX_LENGTH + 1],
    int *count) const;
//new function
int levDistance(const char *str1, const char *str2) const;

当我尝试递归调用此函数时,收到此错误消息:

AvlTree.cpp:412:31: error: no matching function for call to ‘AvlTree<const char*>::transverseTree(AvlNode<const char*>*&, const char*&, char (*&)[34]) const’
                 transverseTree( t->left, word, matchingWords );
                           ^

为什么他们的符号在递归调用的参数类型上?这些是参考文献吗?如果是,我该怎么做?

您忘记在递归调用中传递 count

transverseTree( t->left, word, matchingWords, count );  // Missing count
transverseTree( t->right, word, matchingWords, count ); // Missing count

签名看起来像

void 
AvlTree<Comparable>::transverseTree(AvlNode<Comparable> *t, 
                                    const char *word, 
                                    char matchingWords[100][MAX_LENGTH + 1], 
                                    int *count)

但是你的电话看起来像

transverseTree( t->right, word, matchingWords );

我想你忘了传递 count 指针。

这可能与您的递归调用没有正确的参数有关。

void transverseTree(AvlNode<Comparable> *t, const char *word, char matchingWords[100][MAX_LENGTH + 1], int *count) const;

在这里,当你声明这个函数时,它有4个参数。

但是,当你递归调用这个函数时:

transverseTree( t->left, word, matchingWords );

您忘记了最后一个参数 *count,因此您尝试调用的函数未使用该特定函数签名定义。

& 符号在这里无关紧要;他们只允许传递一个参数作为参考。尽管如此,具有相同类型的非引用参数的函数也将匹配(有效地要求在函数调用之前复制对象),前提是有一个为参数类型定义(显式或默认)的复制构造函数。在这种情况下,对象类型是一个指针,并且为其隐式定义了一个复制构造函数(仅复制值)。所以这没有问题。

递归调用中似乎仍然缺少最后一个参数 count 。这可能是编译错误的原因(当然,除非您在 AvlTree class 中的声明中为其指定了默认值)。