序列化:把对象转化为可传输的字节序列过程称为序列化。
反序列化:把字节序列还原为对象的过程称为反序列化。
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