简体   繁体   中英

Qt C++ operator == overload Qlist not called

My operator == is not beeing called when i use QList or QHashMap

here is my code :

class Node
{
    QString     _state;
    Node*       _parent;
    // for ID generation purpose
    static int  _seqNumber;
    int         _id;
public:
    Node();
    inline bool operator== (const Node &node) const
    {
         return ( _id == node._id  );
    }
 }

Now if i use QHash for example :

    QHash<Node*, double> hashMap* = new QHash<Node*, double>();
    Node* node = new Node();

    hashMap->insert(node, 500);

    // value is never found, because operator== is not being called
    double value = hashMap->value(node); 

I can't get value or compare is node exists in the map because operator== is not called !!

If you can help i would apreciate that.

This is expected behaviour . You are using Node* as your key-type, but there is no special operator==(Node*,Node*) defined.

What you seem to intend is Node .

The Hash key is a pointer( Node* ) not a Node object. so the map or hash is comparing pointers in there. Thus, there's really no need to your operator== .

And you cannot ask compiler to use your function to compare two pointers. because a pointer is a primitive type just like an int . you cannot overload operator== to compare two int s.

So, I think the solution, could be to use your object as hash key like this:

QHash<Node, double> //[1]

or just use pointer and leave the comparison to pointer comparisons.

[1] But then, you'd have to provide a hash function for the QHash to work as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM