Search code examples
c++qtqdebug

Overloading QDebug in QT


In view.h file :

friend QDebug operator<< (QDebug , const Model_Personal_Info &);

In view.cpp file :

QDebug operator<< (QDebug out, const Model_Personal_Info &personalInfo) {
    out << "Personal Info :\n";
    return out;
}

after calling :

qDebug() << personalInfo;

It is suppose to give output : "Personal Info :"

but it is giving an error :

error: no match for 'operator<<' in 'qDebug()() << personalInfo'

Solution

  • Header:

    class DebugClass : public QObject
    {
        Q_OBJECT
    public:
        explicit DebugClass(QObject *parent = 0);
        int x;
    };
    
    QDebug operator<< (QDebug , const DebugClass &);
    

    And realization:

    DebugClass::DebugClass(QObject *parent) : QObject(parent)
    {
        x = 5;
    }   
    
    QDebug operator<<(QDebug dbg, const DebugClass &info)
    {
        dbg.nospace() << "This is x: " << info.x;
        return dbg.maybeSpace();
    }
    

    Or you could define all in header like this:

    class DebugClass : public QObject
    {
        Q_OBJECT
    public:
        explicit DebugClass(QObject *parent = 0);
        friend QDebug operator<< (QDebug dbg, const DebugClass &info){
            dbg.nospace() << "This is x: " <<info.x;
            return dbg.maybeSpace();
        }
    
    private:
        int x;
    };
    

    Works fine for me.