0

我在类中有一个类和一个结构,如下所示:

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

    struct MyStruct
    {
       quint8 val1;
    }
};

我想为结构重载运算符 << 和 >>,但我不知道该怎么做。目前,我确实喜欢这样:

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;
       }
    };
};

但这不行

4

3 回答 3

4

您需要将运算符声明为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;
       }
于 2013-07-17T07:17:15.350 回答
2

通常,您将这些运算符指定为与它们尝试输出的类型相同的命名空间范围内的非成员函数。这是为了允许在使用时进行参数相关查找

class MyClass { [...]
};

QDataStream& operator<<(QDataStream& qstr, MyClass::Mystruct const& rhs) {
     [...]
    return qstr;
}
于 2013-07-17T07:18:23.237 回答
1

我认为添加QDataStream为您的班级成员会很好。在您的意思的上下文中,operator>>只接受一个参数。这是代码:

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;
       }
    };
};
于 2013-07-17T07:08:48.270 回答