我有一个ContactData类和一个持有QList的FriendList类,并且重载了>运算符。contactdata.hclass ContactData{//all public for testingpublic: ContactData(); QString m_name; QString m_description; bool m_online;};QDataStream &operator<<(QDataStream& out, ContactData& contactData);QDataStream &operator>>(QDataStream& in, ContactData* contactData);contactdata.cppQDataStream &operator<<(QDataStream &out, ContactData& contactData){ out << contactData.m_name; out << contactData.m_description; return out;}QDataStream &operator>>(QDataStream &in, ContactData* contactData){ in >> contactData->m_name; in >> contactData->m_description; return in;}朋友清单#include "contactdata.h"typedef QList<ContactData*> TFriendList;class FriendList{...public:TFriendList* m_list;...};QDataStream &operator<<(QDataStream& out, FriendList& list);QDataStream &operator>>(QDataStream& in, FriendList* list);朋友清单QDataStream &operator<<(QDataStream& out, FriendList& list){ for(int i = 0; i < list.size(); i++) { ContactData contact = *list.at(i); out << contact; } return out;}QDataStream &operator>>(QDataStream& in, FriendList* list){ for(int i = 0; i < list->size(); i++) { ContactData* contact = list->m_list->at(i); in >> contact; } return in;}// typedef QList<ContactData*> TFriendList;private: FriendList* m_friendList;保存功能QString path = "/friendlist.bin";QFile file(path);if (file.open(QIODevice::WriteOnly)){ QDataStream out(&file); out << m_friendList; file.close();}加载功能QString path = "/friendlist.bin";QFile file(path);if(file.exists()){ if (file.open(QIODevice::ReadOnly)) { QDataStream in(&file); in >> m_friendList; file.close(); qDebug() << "FriendList.size() = " << m_friendList->size(); }}它确实按期望的方向保存了文件,但不幸的是加载后给了我一个大小为0的空列表。这就是我卡住的地方。有人可以帮忙吗? 最佳答案 从您的代码重建列表:for(int i = 0; i < list->size(); i++)问题是,当您反序列化为空列表时,size()将返回0(或与您必须从磁盘读取的内容完全无关的值),并且无论如何您都必须从流中读取项目,实际的列表并不重要尺寸。此外,list是空的,因此您必须首先创建一个新元素(您不能只调用at(),因为其中没有元素)。您可以在项目前写一个整数(例如),然后在反序列化时读取它:QDataStream &operator>>(QDataStream& in, FriendList* list){ int count = 0; in >> count; for(int i = 0; i < count; i++) { ContactData* contact = new ContactData(); in >> contact; list->m_list->push_back(contact); } return in;}不要忘记在序列化函数中也写count。或者,您可以阅读所有内容,直到输入流结束:QDataStream &operator>>(QDataStream& in, FriendList* list){ int count = 0; in >> count; while (!in.atEnd()) { ContactData* contact = new ContactData(); in >> contact; list->m_list->push_back(contact); } return in;}要完成检查注释中的Kamil said,如果您在序列化过程中没有任何错误,可能只是拼写错误,但是...关于c++ - 保存QList <Class *>并将其加载到文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21186434/ 10-11 18:20