PDA

View Full Version : Using custom class as a key (QSet)



daujeroti
28th April 2011, 09:26
Hello! I have a very simple class, called Node.

Node.h

#ifndef NODE_H
#define NODE_H

#include <QSet>

class Node
{

public:
Node();
Node(const uchar &c);

uchar val;
QSet<Node> childNodes;

bool addChild(const Node& node);

inline bool operator==(const Node &n1, const Node &n2)
{
return n1.val == n2.val;
}

inline uint qHash(const Node &node)
{
return qHash(node.val);
}

};

#endif // NODE_H

Node.cpp

#include "Node.h"

Node::Node()
{
val = -1;
}

Node::Node(const uchar &c)
{
val = c;
}

bool Node::addChild(const Node &node)
{
if(childNodes.contains(node))
return false;

childNodes.insert(node);
return true;
}

I get the following error messages:


'bool Node::operator==(const Node&, const Node&)' must take exactly one argument
no matching function for call to 'qHash(const Node&)'
no match for 'operator==' in key0==((QHashNode<Node, QHashDummyValue*)this)->QHashNode<Node,QHashDummyValue>::key'


What can be the problem?

Thanks in advance!

calhal
28th April 2011, 09:47
The problem is exactly what the compiler says.

First you want to have your == operator more or less like this:

bool operator== ( const Node & other ) const
because you want to compare object "this" with some "other" object.

The second problem is, I think, that qHash function should be implemented outside the class.

MarekR22
28th April 2011, 10:08
Read in documentation of QSet (http://doc.qt.nokia.com/latest/qset.html) last two paragraphs of Detailed Description (http://doc.qt.nokia.com/latest/qset.html#details).

daujeroti
28th April 2011, 21:30
The second problem is, I think, that qHash function should be implemented outside the class.

That's the point! Thank You!

Fallen_
28th April 2011, 21:39
this:

return qHash(node.val);
should be:

return ::qHash(node.val);