繁体   English   中英

以递归方式调用模板类的成员函数

[英]Calling member function of a template class recursively

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

//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类的声明中为它指定了默认值)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM