C++的序列化和反序列化

序列化:把对象转化为可传输的字节序列过程称为序列化。

反序列化:把字节序列还原为对象的过程称为反序列化。

C++代码实现

#include <iostream>
#include <fstream>
 
class Data {
public:
    // write data
    std::ofstream& operator>>(std::ofstream& ofs) {
        ofs.write(reinterpret_cast<char*>(this), sizeof *this);
        return ofs;
    }
    // read data
    std::ifstream& operator<<(std::ifstream& ifs) {
        ifs.read(reinterpret_cast<char*>(this), sizeof *this);
        return ifs;
    }
 
    // data
    char   _c;
    int    _i;
    float  _f;
    double _d;
};
 
// write data
std::ofstream& operator<<(std::ofstream& ofs, Data& d)
{
    return d >> ofs;
}
// read data
std::ifstream& operator>>(std::ifstream& ifs, Data& d)
{
    return d << ifs;
}
 
void print(const Data& d)
{
    std::cout << d._c << ", " << d._i << ", " << d._f << ", " << d._d << std::endl;
}
 
int main(int, char**)
{
    // 序列化
    // write binary file
    std::cout << "write data: " << std::endl;
    Data w1 = {'a', 100, 1.14, 1.14};
    Data w2 = {'b', 200, 2.14, 2.14};
    Data w3 = {'c', 300, 3.14, 3.14};
 
    print(w1);
    print(w2);
    print(w3);
 
    std::ofstream ofs("data.bin", std::ifstream::binary);
    ofs << w1 << w2 << w3;
    ofs.close();
 
    // 反序列化
    // read binary file
    std::cout << "read data: " << std::endl;
    Data r1, r2, r3;
    std::ifstream ifs("data.bin", std::ifstream::binary);
    ifs >> r1 >> r2 >> r3;
    ifs.close();
 
    print(r1);
    print(r2);
    print(r3);
 
    return 0;
}

输出结果

write data:

a, 100, 1.14, 1.14

b, 200, 2.14, 2.14

c, 300, 3.14, 3.14

read data:

a, 100, 1.14, 1.14

b, 200, 2.14, 2.14

c, 300, 3.14, 3.14

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值