模板函数定义的编译错误

compilation errors with template function definition

本文关键字:编译 错误 定义 函数      更新时间:2023-10-16

所以我试图为红黑树制作一个模板,但我不明白为什么有些函数不能编译。以下是规格:

template <class myType>
class redBlackTree
{
private:
    enum treeTraversalOptions {INORDER, PREORDER, POSTORDER, NONE};
    enum nodeColor {RED, BLACK};
    struct nodeType
    {
        myType keyValue;
        nodeColor color;
        unsigned int wrdCount;
        nodeType *left;
        nodeType *right;
        nodeType *parent;
    };
    nodeType *root;
    void destroyTree(nodeType *);
    unsigned int countNodes(nodeType *) const;
    unsigned int height(nodeType *) const;
    nodeType * incCount(myType, nodeType *) const;
    unsigned int getWordCount(myType, nodeType *) const;
    void getMaxNode(nodeType *, unsigned int &, std::string &);
    void printTree(nodeType *, treeTraversalOptions) const;
    nodeType * rightRotate(nodeType *);
    nodeType * leftRotate(nodeType *);
public:
    redBlackTree();
    ~redBlackTree();
    void destroyTree();
    unsigned int countNodes() const;
    void getMaxNode(unsigned int &, std::string &);
    unsigned int height() const;
    bool incCount(myType) const;
    unsigned int getWordCount(myType) const;
    void printTree(treeTraversalOptions) const;
    void insert(myType);
};

这里有一个问题函数:

template <class MyType>
unsigned int redBlackTree<myType>::getWordCount(myType word, nodeType *treeNode) const
{
    if (treeNode)
    {
        if (treeNode->keyValue == word)
            return treeNode->wrdCount;
        else if (word < treeNode->keyValue)
            getWordCount(word, treeNode->left);
        else
            getWordCount(word, treeNode->right);
    }
    return 0;
}

我得到的错误是:"myType"未在此作用域中声明,模板参数1无效,并且模板声明为"unsigned int getWordCount"。

我试过在某些地方添加typename和scope解析操作符,但我不明白为什么它不起作用。

您在某些地方使用了MyType,在其他地方使用了myType

你可以通过改变来修复它

template <class MyType>

template <class myType>

或者标准库中的一般惯例至少是只使用

template <class T>

它有助于在某种程度上区分模板化类型和传统变量。