Q:

QT: Error Overloading the "<<" operator in Qdatastream

I have a class
class budget
{
    float transportation, grocery, food, stationery;
    QString key;
public:
//input output functions here.

};

I created a QHash> and << operators for my class.
QDataStream &operator <<(QDataStream &stream, budget &myclass)
{
    stream<<myclass.getFood();
    stream<<myclass.getGrocery();
    stream<<myclass.getKey();
    stream<<myclass.getStatn();
    stream<<myclass.getTransport();

    return stream;
}

QDataStream &operator >>(QDataStream &stream, budget &myclass)
{
    float f;
    QString s;
    stream>>f;
    myclass.addFood(f);
    stream>>f;
    myclass.addGrocery(f);
    stream>>s;
    myclass.addDate(s);
    stream>>f;
    myclass.addStatn(f);
    stream>>f;
    myclass.addTransport(f);

    return stream;
}

But even now i still get an error:

C:\Users\Karthik\QT\Mendrive-build-simulator-Simulator_Qt_for_MinGW_4_4__Qt_SDK__Debug........\QtSDK\Simulator\Qt\mingw\include\QtCore\qdatastream.h:381:
  error: no match for 'operator<<' in
  'operator<<(((QDataStream&)((QDataStream*)out)), ((const
  QString&)((const QString*)it.QHash::const_iterator::key with
  Key = QString, T = budget))) << it.QHash::const_iterator::value with Key = QString, T = budget'

Why is this happening? Apparently the >> operator seems to be overloaded i get the error only for the << operator.
Thanks.

A:

The error stems from the declaration of the function signatures. Change your declarations from:
QDataStream &operator <<(QDataStream &stream, budget &myclass);
QDataStream &operator >>(QDataStream &stream, budget &myclass);

to:
QDataStream &operator <<(QDataStream &stream, const budget &myclass);
QDataStream &operator >>(QDataStream &stream, budget &myclass);

The same problem has described here
Sorry I have missed one thing. Methods must be declares as friends also. So I have tried it out and here is working result;
class budget
{
  float transportation, grocery, food, stationery;
  QString key;
public:
  budget() {}

friend QDataStream &operator <<(QDataStream &stream, const budget &myclass) {

      stream<< myclass.food;
      stream<< myclass.grocery;
      stream<< myclass.key;
      stream<< myclass.stationery;
      stream<< myclass.transportation;

    return stream;

}
friend QDataStream &operator >>(QDataStream &stream, budget &myclass) {

    stream >> myclass.food;
    stream >> myclass.grocery;
    stream >> myclass.key;
    stream >> myclass.stationery;
    stream >> myclass.transportation;
    return stream;

}

update
To answer your question regarding friend functions let me point you to the answer already available here

