C++中重载输入输出操作符

作者:冯利美,华清远见嵌入式培训中心讲师。

QT中封装了数据流类QDataStream和模板类QList。有时需要往流里写模板类对象,但是,QDataStream中,没有参数匹配的运算符重载函数operator<< 。此时需要重载输入输出操作符函数,使之能支持模板类。

比如,自定义一个类:

#include <QString>
        class UserType
        {
        public:
                UserType();
                QString id;
                QString name;
        };

实例化模板类QList<UserType>,声明一个UserType类型的对象链表:

UserType u1, u2;
        u1.id = "1";
        u1.name = "1";
        u2.id = "2";
        u2.name = "2";
        QList<UserType> list;
        list.append(u1);
        list.append(u2);

假如需要往QDataStream流中写这个模板类对象。代码如下:

QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out << list;

编译会报错,QDataStream & operator<< (const QList<UserType> & list )函数不存在。同样,从流中读出一个模板类对象,也会有类似的错误。因为在QT的QDataStream类中,没有定义好的参数匹配的输入输出操作符函数operator<<。

解决问题的办法是,实现两个非成员函数。代码如下:

QDataStream & operator<< ( QDataStream & out, const QList<UserType> & list )
        {
                int i;
                for (i = 0; i < list.count(); i++)
                {
                        out << list.at(i).id << list.at(i).name;
                }
                return out;
        }
        QDataStream & operator>> ( QDataStream & in, QList<UserType> & list )
        {
                while (!in.atEnd())
                {
                        UserType t;
                        in >> t.id;
                        in >> t.name;
                        list.append(t);
                }
                return in;
        }

这样往流里写模板类对象,就不会出错,当从流中读出数据时,就用到了operator>>函数。示例代码如下:

MainWindow::MainWindow(QWidget *parent) :
                QMainWindow(parent),
                ui(new Ui::MainWindow)
        {
                ui->setupUi(this);

        UserType u1, u2;
                u1.id = "1";
                u1.name = "1";
                u2.id = "2";
                u2.name = "2";
                QList<UserType> list;
                list.append(u1);
                list.append(u2);
                QByteArray block;
                QDataStream out(&block, QIODevice::WriteOnly);
                out << list;
                //……
                QList<UserType> list2;
                QDataStream in(&block, QIODevice::ReadOnly);
                in >> list2;
                int i;
                for (i = 0; i < list2.count(); i++)
                {
                        ui->listWidget->addItem(list2.at(i).id);
                        ui->listWidget->addItem(list2.at(i).name);
                }
        }

你可能感兴趣的:(C++)