QDataStream(自定义数据结构序列化)

 1 class Student{
 2 
 3 public:
 4 
 5     QString name;
 6     int age;
 7     double score;
 8 
 9     Student(const QString& _name = "", int _age = 0, double _score = 0.0)
10         : name(_name)
11         , age(_age)
12         , score(_score)
13     {
14 
15     }
16 
17     friend QDataStream& operator << (QDataStream& stream, const Student& stu)
18     {
19         stream<<stu.name<<stu.age<<stu.score;
20         return stream;
21     }
22 
23     friend QDataStream& operator >>(QDataStream& stream, Student& stu)
24     {
25         stream >> stu.name >> stu.age >> stu.score;
26         return stream;
27     }
28 
29 };
30 
31 
32 void saveStudent(const Student& stu)
33 {
34     QFile file("student.dat");
35     file.open(QIODevice::WriteOnly | QIODevice::Append);
36     QDataStream ds(&file);
37     ds << stu;
38     file.close();
39 }
40 
41 void readStudent()
42 {
43     QFile file("student.dat");
44     file.open(QIODevice::ReadOnly);
45     QDataStream ds(&file);
46     Student stu;
47     while(!ds.atEnd())
48     {
49         ds >> stu;
50         qDebug() << "{" << stu.name << ", " << stu.age << ", " << stu.score << "}";
51     }
52     file.close();
53 }
54 
55 
56 int main(int argc, char **argv)
57 {
58     //LOG_BEG
59     QApplication app(argc, argv);
60     MainWindow w;
61     w.show();
62     Student stu1{"Alice", 10, 87.1};
63     Student stu2{"Linda", 14, 67.2};
64     Student stu3{"Bruce", 13, 57.3};
65     saveStudent(stu1);
66     saveStudent(stu2);
67     saveStudent(stu3);
68     readStudent();
69     //LOG_END
70     return app.exec();
71 }
原文地址:https://www.cnblogs.com/endenvor/p/14075286.html