2017-09-15 162 views
0

我有下面列出的对象。C++序列化包含其他对象数组的对象

class Customer 
{ 
private: 
    std::string customerName; 
    std::string customerLastName; 
    std::string customerIdentityNumber; 
    std::vector<std::unique_ptr<Account>> customerAccounts; 

} 

如何将序列化此对象?我试过找到例子,但是这些都使用一些复杂的库。当然必须有一个更简单的方法?

来自Java这对我来说是新的。

+0

你试过了什么,'Account'是什么? – Rama

+1

您将不再需要确定每个类型都定义了“operator >>”和“operator <<”,然后将其写入文件或使用类似boost :: serialization的库。 – NathanOliver

回答

1

我真的建议一个序列化库等boost::serialization

它的一个伟大的图书馆,使用方便,速度极快,并且已经不仅仅是这更多!

这正是你要找的。

0

我更喜欢一个非常简单和基本的实现。假设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); 
     } 
    } 
} 

的代码是不言自明的。但想法是归档计数,然后是每个元素。这有助于从文件反序列化。

相关问题