我更喜歡一個非常簡單和基本的實現。假設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