c++ - 重载的Double Equal运算符无法正常工作

标签 c++ class operator-overloading doubly-linked-list

它是一个长双链表代码。但是问题是当我重载运算符时,我认为函数没有被调用。我曾尝试在此处放置调试行打印,但此操作从未显示出来。
所以我想如果我的双链表中的两个相等,它应该显示为true。

class Node
{
    friend class Dlist;
private:
    string s;
    string language;
    int noOfNode;
    Node * Next;
    Node * Prev;
};


class Dlist
{
private:
    Node * Header;
    Node * Trailer;
    int n;

public:
    Dlist();//default constructor
    void AddFront(string e,string lang);
    void Print();
    void AddBack(string e,string lang);
    void RemoveFront();
    void RemoveBack();
    int Empty(){ if (Header->Next==Trailer) return 1 ; else return 0;}
    int CountLanguage(string lang);
    int search (string r);
    void RemoveWord(string tempW);
    void changeIndex(Node* node,int newIndex);
    void sortDLL();
    void PrintRev();
    void AddInOrder(string s, string language);
    bool operator==(const Dlist &Q);
};
bool Dlist::operator ==(const Dlist &Q)
{
    Node*tempL1=Header->Next;
    Node *tempL2=Q.Header->Next;
    int count=0;
    cout<<"here"<<endl;
    if(n==Q.n)
    {
        while(tempL1!=Trailer && tempL2!=Q.Trailer)
        {
            if(tempL1->s==tempL2->s && tempL1->language==tempL2->language
                ){
                tempL1=tempL1->Next;
                tempL2=tempL2->Next;
            }
            else return false;
        }
        return true;
    }
    else
    return false;

}
int main()
{
    Dlist *x = new Dlist;
    Dlist *y = new Dlist;
    Dlist *z = new Dlist;

    inputX();
    inputY();
    cout<<endl<<"test if the first list and the second are equal?? :"<<endl;
    cout<<(x==y)<<endl;
    return 0;
}

最佳答案

对于初学者,应使用限定符const声明运算符(operator)

bool operator==(const Dlist &Q) const;
在此声明中
cout<<(x==y)<<endl;
使用的表达式是两个指针xy的比较,声明为
Dlist *x = new Dlist;
Dlist *y = new Dlist;
您需要比较尖的对象,例如
cout<<( *x == *y )<<endl;
请注意,此代码段中存在逻辑错误
    while(tempL1!=Trailer && tempL2!=Q.Trailer)
    {
        if(tempL1->s==tempL2->s && tempL1->language==tempL2->language
            ){
            tempL1=tempL1->Next;
            tempL2=tempL2->Next;
        }
        else return false;
    }
    return true;
代替声明
    return true;
你应该写
    return tempL1 == Trailer && tempL2 == Q.Trailer;

关于c++ - 重载的Double Equal运算符无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64703124/

相关文章:

c++ - 在全屏模式游戏中运行exe文件

c++ - 为什么我不能在 while 循环的测试部分中放置变量声明?

c++ - 如何链接多个运算符[]

c++ - C++ 中的 union 和按位运算

C++ 重载运算符两次,一次返回非 const 引用,另一次返回 const 引用,偏好是什么?

c++ - 带纹理的图像如何阈值?通过tesseract识别

c++ - 右值引用的生命周期

java - 主类: Manifest - how to define an entry point with arguments

c++ - 在 C++ 中包含头文件时的循环类依赖

java - 原始包装器和静态 "TYPE"类对象