0

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

federem
  • 299
  • 1
  • 6
  • 17
  • [operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading) – chris Jul 17 '13 at 07:05

3 Answers3

4

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;
       }
fatihk
  • 7,789
  • 1
  • 26
  • 48
  • I try to declare the operators as friend ; it is OK for operator<< but I have this error for operator>> `erreur : no match for 'operator>>' in 'in >> _myStruct.val1'` – federem Jul 17 '13 at 07:50
  • Sorry, it is OK, the solution needed to be cleaned – federem Jul 17 '13 at 08:05
2

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;
}
ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
1

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;
       }
    };
};
Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
lulyon
  • 6,707
  • 7
  • 32
  • 49
  • I expect the OP wanted to say `someQDataStream << MyStructObj;`. – chris Jul 17 '13 at 07:17
  • @chris It is OK. I get what you mean. You mean overload operator<< without inheritance of QDataStream class and parameter passing. The answer that declare the operators as friend is suitable for your question. – lulyon Jul 17 '13 at 07:39