我有一个 ContactData 类和一个持有 QList 的 FriendList 类,并且我重载了 << / >> 运算符。
联系人数据.h
class ContactData
{
//all public for testing
public:
ContactData();
QString m_name;
QString m_description;
bool m_online;
};
QDataStream &operator<<(QDataStream& out, ContactData& contactData);
QDataStream &operator>>(QDataStream& in, ContactData* contactData);
联系人数据.cpp
QDataStream &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;
}
好友列表.h
#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);
好友列表.cpp
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 的空列表。这就是我卡住的地方..
任何人都可以帮忙吗?