federem
federem

Reputation: 299

Overload operator<< and >> in a c++ struct

I have a class and a structure inside the class like that :

class MyClass : public QObject
{
public:
    ....

    struct MyStruct
    {
       quint8 val1;
    }
};

I would like to overload the operators << and >> for the struct, but I don't know how to do. For the moment, I do like that :

class MyClass : public QObject
{
public:
    ....

    struct MyStruct
    {
       quint8 val1;

       QDataStream &operator<<(QDataStream &out, const MyStruct& _myStruct)
       {
           out << _myStruct.val1;
           return out;
       }

       QDataStream &operator>>(QDataStream &in, MyStruct& _myStruct)
       {
           in >> _myStruct.val1;
           return in;
       }
    };
};

but it is not OK

Upvotes: 0

Views: 6422

Answers (3)

lulyon
lulyon

Reputation: 7225

I think Adding QDataStream as your class member will be fine. In the context which you mean, operator>> only accept one parameter. Here is the code:

class MyClass : public QObject
{
private:
QDataStream in;
QDataStream out;
...

public:
    ....

    struct MyStruct
    {
       quint8 val1;

       QDataStream &operator<<(const MyStruct& _myStruct)
       {
           out << _myStruct.val1;
           return out;
       }

       QDataStream &operator>>(MyStruct& _myStruct)
       {
           in >> _myStruct.val1;
           return in;
       }
    };
};

Upvotes: 1

ComicSansMS
ComicSansMS

Reputation: 54589

Usually you specify those operators as non-member functions in the same namespace scope as the type they are trying to output. This is to allow for argument-dependent-lookup upon use.

class MyClass { [...]
};

QDataStream& operator<<(QDataStream& qstr, MyClass::Mystruct const& rhs) {
     [...]
    return qstr;
}

Upvotes: 2

fatihk
fatihk

Reputation: 7919

you need to declare the operators as friend:

       friend QDataStream &operator<<(QDataStream &out, const MyStruct& _myStruct)
       {
           out << _myStruct.val1;
           return out;
       }

       friend  QDataStream &operator>>(QDataStream &in, MyStruct& _myStruct)
       {
           in >> _myStruct.val1;
           return in;
       }

Upvotes: 4

Related Questions