The Data flow class Qdatastream and template class qlist are encapsulated in QT. Sometimes it is necessary to write a template class object into the stream, but in Qdatastream, there is no parameter matching operator overload function operator<<. The input and output operator functions need to be overloaded to support the template class. For example, custom a class: #include <qstring>class usertype{public:usertype (); QString ID; QString name;}; Instantiate the template class Qlist<usertype>, declares an object-linked list of usertype types: usertype u1, u2;u1.id = "1"; u1.name = "1"; u2.id = "2"; u2.name = "2"; Qlist<usertype> List;list.append (U1); List.append (U2); If you need to write this template class object into the Qdatastream stream. The code is as follows: Qbytearray block; Qdatastream out (&block, qiodevice::writeonly); out << list; Compile error, Qdatastream & operator<< (const qlist<usertype> & list) function does not exist. Similarly, there is a similar error in reading a template class object from the stream. Because in Qt's Qdatastream class, there is no well-defined parameter matching input-output operator function operator<<. The solution to this problem is to implement two non-member functions. The code is as follows: 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> &amP List) {while (!in.atend ()) {usertype t;in >> t.id;in >> t.name;list.append (t);} return in;} In this way, the template class object is written into the stream, and the operator>> function is used when the data is read from the stream. The sample code is as follows: 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); >> list2;int i;for (i = 0; i < List2.count (); i++) {ui->list Widget->additem (list2.at (i). ID), Ui->listwidget->additem (list2.at (i). name);}}
Overloaded input and output operators in C + +