How to implement << in a class for output to qDebug?
-
I want to implement an override for the operator << in my class so I can dump data to qDebug, what I've tried so far is obviously wrong.
I have overloaded the operator << in another class, prototype:
clsJSON& operator<<(const QVariant& crvarData);
Implementation:
clsJSON& clsJRONRef::operator<<(const QVariant& crvarData) { int intLength(intArrayLength()); if ( intLength >= 0 ) { QString strRef(clsJRONRef::crstrMakeArrayRef(intLength)); const QByteArray carybytRef[strRef::toLatin1()); const char* cpszRef(carybytRef.data()); QString strArrayLength(QString("%1%2%2") .arg(clsJSON::mscszALSM) .arg(++intLength) .arg(clsJSON::mscszALEM)); mpobjJSON->setProperty(cpszRef, crvarData); mpobjJSON->setProperty(mcpszRef, QVariant(strArrayLength)); mblnValid = true; } return *mpobjJSON; }
The above works and allows me to do stuff like:
QByteArray arybytData; clsJSON objDemo, objJSONarray; arybytData.append("ABCDEFGH"); objDemo["bytearray"] = arybytData; objJSONarray["array"] << 1; objJSONarray["array"] << 2; objJSONarray["array"] << 3; objJSONarray["array"] << "a"; objJSONarray["array"] << "b"; objJSONarray["array"] << "c";
What I now want to do is the inverse, using the << operator to extract data from the object, something like:
qDebug() << objDemo["bytearray"]; qDebug() << objJSONarray;
I've tried adding the prototype:
friend ostream& operator<<(ostream& os, const clsJSON& objJSON);
With implementation:
ostream& clsJSON::operator<<(ostream& os, const clsJSON& crobjJSON) { ... }
When I try to build this I get:
std::ostream& clsJSON::operator<<(std::ostream&, const clsJSON&)' must take exactly one argument
-
If you add it as class function you must not add
const clsJSON& crobjJSON
- the value is in your object, also the function must be const in this case. If you want it as free function then the signature is correct except that you need qDebug instead std::ostream if you want to use it for qDebug - see https://doc.qt.io/qt-5/qdebug.html#writing-custom-types-to-a-stream -
This post is deleted!