我更喜欢一个非常简单和基本的实现。假设Serialize()
函数已经为Account
类实现。
Customer
类的Serialize()
功能的实现可以是:
void Customer::Serialize(Archive& stream)
{
if(stream.isStoring()) //write to file
{
stream << customerName;
stream << customerLastName;
stream << customerIdentityNumber;
stream << customerAccounts.size(); //Serialize the count of objects
//Iterate through all objects and serialize those
std::vector<std::unique_ptr<Account>>::iterator iterAccounts, endAccounts;
endAccounts = customerAccounts.end() ;
for(iterAccounts = customerAccounts.begin() ; iterAccounts!= endAccounts; ++iterAccounts)
{
(*iterAccounts)->Serialzie(stream);
}
}
else //Reading from file
{
stream >> customerName;
stream >> customerLastName;
stream >> customerIdentityNumber;
int nNumberOfAccounts = 0;
stream >> nNumberOfAccounts;
customerAccounts.empty(); //Empty the list
for(int i=0; i<nNumberOfAccounts; i++)
{
Account* pAccount = new Account();
pAccount->Serialize(stream);
//Add to vector
customerAccounts.push_back(pAccount);
}
}
}
的代码是不言自明的。但想法是归档计数,然后是每个元素。这有助于从文件反序列化。
来源
2017-09-15 22:20:20
MKR
你试过了什么,'Account'是什么? – Rama
您将不再需要确定每个类型都定义了“operator >>”和“operator <<”,然后将其写入文件或使用类似boost :: serialization的库。 – NathanOliver