Reputation: 745
I am newbie in Qt and learning to handle how QHash works. On working with this example I dont understand why this throws me an error. I may miss something, but please guide me to learn this.
main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QHash<QString,Person> hash;
QString key="1";
Person p;
p.name = name;
p.number = an;
hash.insert(key,p);
return a.exec();
}
person.h
class Person
{
public:
Person();
Person(QString name,QString num);
bool operator==(const Person & other) const; //== overloading to assign in QHash
QString name,number;
};
person.cpp
Person::Person()
{
}
Person::Person(QString name, QString num)
{
this->name=name;
this->number=num;
}
bool Person::operator==(const Person & other) const
{
bool state;
if (name == other.name )
state = true;
else
state = false;
return state;
}
and the error is:-'qHash':none of the 17 overloads could convert all the argument type.I knw im missing something.Please guide me.
Upvotes: 5
Views: 16232
Reputation: 12931
You need the global qHash()
function.
A QHash's key type has additional requirements other than being an assignable data type: it must provide operator==(), and there must also be a qHash() function in the type's namespace that returns a hash value for an argument of the key's type.
See this for more info about that.
Upvotes: 5
Reputation: 7458
The code you've provided is not complete and not compilable - e.g. The symbol name is not found, no includes.
The op == is not required when you use the class as value. The only one requirement for value-classes - a default constructor.
I think you problem was something else. If you provided the complete code and the complete list of errors I could tell you what exactly.
Below you'll find the working version of you code-snippet. (For simplicity, everything in one file)
main.cpp
#include <QApplication>
#include <QHash>
#include <QString>
class Person
{
public:
Person(QString name=QString::null,QString num=QString::null);
QString name,number;
};
Person::Person(QString _name, QString _num)
:name(_name),number(_num)
{
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QHash<QString,Person> hash;
QString key="1";
Person p("Orhan Kemal", "1914");
hash.insert(key,p);
return a.exec();
}
Regards, Valentin
EDIT: Initialized members not in body
Upvotes: 0