Subtle difference in the use of QDebug for your own class
-
QDebug objects are part of Qt's debug facilities and handy to use.
For instance it may be used as a substitute of C++ std::cout and std::cerr :
@
int intNr = 12;
qDebug() << intNr;
@The reading of "the documentation":http://qt-project.org/doc/qt-4.8/qdebug.html provides examples and also a sample implementation for writing output operators for your own classes.
The casual reader will assume that the class is simply another way of implementing some sort of an output stream. Well, the use in your implementation is slightly different or at least it has to be for some compilers.
At first an example parameter list for overwriting an std::ostream can be found in the Internet e.g. "here":http://www.cplusplus.com/reference/iostream/ostream/operator<</
@ostream& operator<< (short val)@The different versions show a reference of the output stream as a return value and also some parameter lists show an ostream &.
This looks quite similar to the definition of the output operators for some standard types "(e.g.)":http://qt-project.org/doc/qt-4.8/qdebug.html#operator-lt-lt-5
@
QDebug & QDebug::operator<< ( signed short i )
@Casual reading of the documentation, and the thinking of the handling is identical, may lead to following implementation:
@
#include <QtCore/QCoreApplication>
#include <QDebug>class MyClassA
{
int A1;
int A2;
public:
MyClassA ( int i1, int i2 )
: A1 ( i1 )
, A2 ( i2 ) {}
int getA1 () const {return A1;};
int getA2 () const {return A2;};
};QDebug & operator<< ( QDebug & os, const MyClassA & val )
{
os << val.getA1() << " " << val.getA2();
return os;
}int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClassA aval( 1, 12 );qDebug() << aval << " " << aval; return a.exec();
}
@
At least some compilers will compile without a note and the application will function as supposed. Among those compilers the one of MS VC 2005.Porting to minGW will unveil a surprise. A compile error is displayed and the compilation is stopped.
Modifying
@
QDebug & operator<< ( QDebug & os, const MyClassA & val )
@
to
@
QDebug operator<< ( QDebug os, const MyClassA & val )
@
solves finally the problem. The second line follows the example given in the documentation:
[quote]
Writing Custom Types to a Stream
Many standard types can be written to QDebug objects, and Qt provides support for most Qt value types. To add support for custom types, you need to implement a streaming operator, as in the following example:
@QDebug operator<<(QDebug dbg, const Coordinate &c)
{
dbg.nospace() << "(" << c.x() << ", " << c.y() << ")";return dbg.space();
}@
[/quote]