C++ C++;序列化包含其他对象数组的对象

C++ C++;序列化包含其他对象数组的对象,c++,C++,我有下面列出的对象 class Customer { private: std::string customerName; std::string customerLastName; std::string customerIdentityNumber; std::vector<std::unique_ptr<Account>> customerAccounts; } class客户 { 私人: std::字符串客户名称; std::字

我有下面列出的对象

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

}
class客户
{
私人:
std::字符串客户名称;
std::字符串customerLastName;
std::字符串customerIdentityNumber;
std::矢量客户帐户;
}
如何序列化这个对象?我尝试过寻找示例,但这些示例都使用了一些复杂的库。肯定有更简单的方法吗


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

我真的建议使用序列化库,例如

这是一个很棒的库,易于使用,速度极快,而且不仅仅是这个


这正是您想要的。

我更喜欢一个非常简单和基本的实现。让我们假设
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);
        }
    }
}
void Customer::序列化(归档和流)
{
if(stream.isStoring())//写入文件
{
流>customerLastName;
流>>customerIdentityNumber;
int nnnumberofaccounts=0;
流>>nn计数;
customerAccounts.empty();//清空列表
for(int i=0;iSerialize(stream);
//添加到向量
customerAccounts.push_back(打包计数);
}
}
}

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

您尝试了什么,什么是
帐户
?您将确保每种类型都有
操作符>
操作符