使用模板和C++中的错误

Working with templates and error in C++

本文关键字:错误 C++      更新时间:2023-10-16

我正在尝试使用模板实现一棵红黑树。例如,将项插入树时,键和项都应是泛型类型。到目前为止,我实现了一个头文件,其中包含要实现的结构和函数。但是,我不知道我是否以正确的方式使用模板。另外,当我尝试实现"插入"功能时,IDE 给出了错误:"void RedBlackTree::InsertKey(Item*&, Key*&)"的原型与类"RedBlackTree"中的任何内容都不匹配 RedBlackTree.h

这是我的头文件:

#ifndef REDBLACKTREE_H_
#define REDBLACKTREE_H_
template <class Item, class Key>
class RedBlackTree
{
    typedef enum
    {
        BLACK,
        RED
    }ColourNode;
    typedef struct RBT
    {
        struct RBT *left;
        struct RBT *right;
        struct RBT *parent;
        struct RBT *root;
        ColourNode colour;
        Item item;
        Key key;
    }RBTNode;
    public:
        ~RedBlackTree(); // destructor
        RedBlackTree(Item, Key); // default constructor
        void InsertKey(Item, Key);
        int InsertFixUp(Item, Key);
        int RemoveKey(Item, Key);
        int FindKey(Item, Key);
    private:
        RedBlackTree<Item, Key> *rootPointer;
        RedBlackTree<Item, Key> *NILL_LEAF;
};
template <class Item, class Key>
void RedBlackTree<Item, Key>::InsertKey(Item *&T, Key *&z)
{
    //node* nil=tree->nil;
    //node* root=tree->root;
    RBTNode *y;
    RBTNode *x;
    y=T->nil;
    x=T->root;
    while(x != T->nil)
    {
        y=x;
        if((z->key)<(x->key))
            x=x->left;
        else
            x=x->right;
    }
    y=z->parent;
    if(y == T->nil)
        z=T->root;
    else
    if((z->key)<(y->key))
        z=y->left;
    else
        z=y->right;
        z->left=T->nil;
        z->right=T->nil;
        z->colour=RED;
        InsertFixUp(T,z);
}
#endif /* REDBLACKTREE_H_ */

提前谢谢。

问题是要InsertKey的参数类型与声明不匹配。在声明中,参数是ItemKey的,在实现中它们是Item*&Key*&的(对指针的引用)。这些需要匹配。

void InsertKey(Item, Key);
               ^^^^  ^^^
void RedBlackTree<Item, Key>::InsertKey(Item *&T, Key *&z)
                                        ^^^^^^^   ^^^^^^
您必须将

函数(模板)的实现移动到类定义中。

template <class Item, class Key>
class RedBlackTree
{
//...
public:
    ~RedBlackTree(); // destructor
    RedBlackTree(Item, Key); // default constructor
    void InsertKey(Item *&T, Key *&z)
    {
        //...
    }
    //...
};