Qt5 Tutorial QFile (Serialization II : class) - 2020
In this tutorial, we will learn how to serialize a class. This is the continuation of the previous tutorial, QFile (Serialization).
We want to serialize a class which has two members. But unlike the previous example which is serializing primitive variables, this tutorial is dealing with a class. As we may already know, we cannot do cin or cout directly on an object of a class because it does not know how to input/output from/to a class.
Therefore, operators (<< and >>) need be overloaded.
This tutorial is almost the same except those operator overloadings:
Here is the source code, main.cpp:
#include <QCoreApplication> #include <QFile> #include <QDataStream> #include <QString> #include <QDebug> class Student { public: int ID; QString Name; // ostream, << overloading friend QDataStream &Student;::operator<<(QDataStream &out;, const Student &s;) { out << s.ID << s.Name; return out; } // istream, >> overloading friend QDataStream &Student;::operator>>(QDataStream ∈, Student &s;) { s = Student(); in >> s.ID >> s.Name; return in; } }; void Save() { Student s1; s1.ID = 1; s1.Name = "Ravel"; Student s2; s2.ID = 2; s2.Name = "Schonberg"; QString filename = "C:/Qt/Test/st.txt"; QFile file(filename); if(!file.open(QIODevice::WriteOnly)) { qDebug() << "Could not open " << filename; return; } QDataStream out(&file;); out.setVersion(QDataStream::Qt_5_1); out << s1 << s2; file.flush(); file.close(); } void Load() { Student s1; Student s2; s2.ID; s2.Name; QString filename = "C:/Qt/Test/st.txt"; QFile file(filename); if(!file.open(QIODevice::ReadOnly)) { qDebug() << "Could not open " << filename; return; } QDataStream in(&file;); in.setVersion(QDataStream::Qt_5_1); in >> s1 >> s2; file.close(); qDebug() << s1.Name << "'s ID is " << s1.ID; qDebug() << s2.Name << "'s ID is " << s2.ID; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Save(); Load(); return a.exec(); }
After we read it back, we get the output like this:
"Ravel" 's ID is 1 "Schonberg" 's ID is 2
Great!
Successful class serialization.
For more on operator overloading, please visit my C++ tutorial, Operator Overloading.
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization