我有下面列出的对象。
class Customer
{
private:
std::string customerName;
std::string customerLastName;
std::string customerIdentityNumber;
std::vector<std::unique_ptr<Account>> customerAccounts;
}
如何序列化这个对象呢?我尝试过查找示例,但这些都使用了一些复杂的库。当然必须有一个更简单的方法吗?
来自Java这对我来说是新的。
答案 0 :(得分:1)
答案 1 :(得分:0)
我更喜欢非常简单和基本的实现。让我们假设已经为Serialize()
类实现了Account
函数。
Serialize()
类的Customer
函数的实现可以是:
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);
}
}
}
代码不言自明。但想法是归档计数,然后是每个元素。从文件反序列化时的帮助。