2017-09-15 163 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); 
     } 
    } 
} 

的代碼是不言自明的。但想法是歸檔計數,然後是每個元素。這有助於從文件反序列化。

相關問題