首页 > 解决方案 > 二叉树模板类中的运算符'=='和'>'不匹配 - c++

问题描述

我对二叉搜索树很陌生,所以请多多包涵。我有一个二叉搜索树类,我首先为整数创建了它。它工作正常,所以我不得不将它转换为模板类,以便它可以处理对象。现在,当尝试将对象作为节点插入时,我得到了这些错误。我知道这意味着我可能不得不重载我的 '==' 和 '>' 运算符,但这真的有必要吗?如果是这样,我的重载需要什么样的逻辑才能正确比较这两种类型?

他们需要布尔返回吗?对不起,我只是在学习 BST。

插入节点方法:

template <class T>
void Bst<T>::insertNode(const T& insertItem)
{
    nodeType<T> *current;
    nodeType<T> *trailCurrent = nullptr;
    nodeType<T> *newNode;

    newNode = new nodeType<T>;
    newNode->info = insertItem;
    newNode->lLink = nullptr;
    newNode->rLink = nullptr;

    if(root == nullptr)
        root = newNode;
    else
    {
        current = root;
        while(current != nullptr)
        {
            trailCurrent = current;
            if(current->info == insertItem)
            {
                cout << "The item to be inserted is already ";
                cout << "in the tree -- duplicates are not "
                << "allowed." << endl;
                return;
            }
            else if(current->info > insertItem)
                current = current->lLink;
            else
                current = current->rLink;
        }
        if(trailCurrent->info > insertItem)
            trailCurrent->lLink = newNode;
        else
            trailCurrent->rLink = newNode;

    }
}

错误:no match for 'operator==' (operand types are 'Date' and 'const Date')|

if(current->info == insertItem)

和错误:no match for 'operator>' (operand types are 'Date' and 'const Date')|

else if(current->info > insertItem)

这就是我调用 insertNode 的地方:

    ifstream infile("date.txt");
    Date dateObj;
    string date1;
    stringstream date;

    Bst<Date> dateTree;

    while(getline(infile, date1))
    {
        stringstream date1;
        string day;
        string month;
        string year;

        getline(date1,day,'/');
        getline(date1,month,'/');
        getline(date1,year);

        dateObj.SetDay(day);
        dateObj.SetMonth(month);
        dateObj.SetYear(year);
        dateTree.insertNode(dateObj);
        dateTree.inOrderTraversal();
    }

标签: c++binary-treeoperator-keyword

解决方案


推荐阅读