【问题标题】:Working with templates and error in C++在 C++ 中使用模板和错误
【发布时间】:2013-12-28 12:35:54
【问题描述】:

我正在尝试使用模板来实现一棵红黑树。例如,当向树中插入一个项目时,键和项目都应该是泛型类型。到现在为止,我实现了一个头文件,它由一个结构和要实现的函数组成。但是,我不知道我是否以正确的方式使用模板。此外,当我尝试实现“插入”功能时,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 原型确实不匹配。一种是Item,另一种是Item*&amp;,这是两种截然不同的类型。

标签: c++ tree


【解决方案1】:

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

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

【讨论】:

  • 我试图在我的主函数中创建一个 RedBlackTree 的实例,但它不接受它:RedBlackTree t1;
  • 我解决了,但实例没有找到我的函数'InsertKey':t1.InsertKey(arr[i]);
  • @user3136756 该函数接受两个参数。你只给一个。
  • 是的,我知道,但是实例 t1 甚至找不到方法 'InsertKey',因为它显示错误:方法 'insertkey' 无法解析
【解决方案2】:

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

template <class Item, class Key>
class RedBlackTree
{
//...
public:
    ~RedBlackTree(); // destructor
    RedBlackTree(Item, Key); // default constructor

    void InsertKey(Item *&T, Key *&z)
    {
        //...
    }

    //...
};

【讨论】:

  • 我解决了这个问题。但是,当我按照您的方式尝试时,出现了很多错误
  • 我的错 - 我认为 InsertKey() 使用其他类型名称。编辑了帖子。
猜你喜欢
  • 1970-01-01
  • 2021-03-12
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多