Overloading QDataStream '<<' and '>>' operator help



  • Hello all!

    Was hoping somebody could help me with an issue I've run into regarding the overloading of the '>>' and '<<' operators for use with a custom class and QDataStream. I'm trying to create a class and then setup overloaded operators for streaming with a QDataStream, but am getting compilation errors. I've attached a simplified version of the code I'm trying to get working along with the error message below.

    Thanks!

    main.cpp:

    #include "class1.h"
    #include <QCoreApplication>
    #include <QDataStream>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        // No datastream has been setup, this is yet to be implemented.
        QDataStream myStream;
        class1 myClass;
    
        myClass << myStream;
    
        return a.exec();
    }
    

    class1.cpp:

    #include "class1.h"
    
    class1::class1(QObject *parent) : QObject(parent)
    {
    
    }
    
    QDataStream & operator>> (QDataStream& stream, class1& image)
    {
        stream >> image.myString;
        return stream;
    }
    
    QDataStream & operator<< (QDataStream& stream, const class1& image)
    {
        stream << image.myString;
        return stream;
    }
    

    class1.h

    #ifndef CLASS1_H
    #define CLASS1_H
    
    #include <QDataStream>
    #include <QObject>
    #include <QString>
    
    class class1 : public QObject
    {
        Q_OBJECT
    public:
        explicit class1(QObject *parent = nullptr);
    
        friend QDataStream & operator>> (QDataStream& stream, class1& image);
        friend QDataStream & operator<< (QDataStream& stream, const class1& image);
    
    private:
        QString myString = "default";
    };
    
    #endif // CLASS1_H
    

    error:

    main.cpp:13: error: no match for 'operator<<' (operand types are 'class1' and 'QDataStream')
         myClass  << myStream;
                  ^
    


  • @Fwomp Hi, friend. Welcome.

    Your code's syntax was wrong.

    QDataStream myStream;
        class1 myClass;
    
        ///< myClass << myStream; ///< Its wrong.
       myStream >> myClass; /// stream => myClass,
       myStream << myClass; /// myClass => stream, 
    

    Because, you defined

    friend QDataStream & operator>> (QDataStream& stream, class1& image); ///< stream is first arguments, class is second argument
    friend QDataStream & operator<< (QDataStream& stream, const class1& image);
    

    if you defined like below:

        friend QDataStream & operator>> (class1& image,QDataStream& stream); ///< first is class and second is stream.
        friend QDataStream & operator<< (const class1& image,QDataStream& stream);
    

    you will right:

    class1 >> stream;
    


  • @joeQ Thanks that's solved it!



  • @Fwomp I modified my answer.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.