没有标准库类可以实现序列化一样的方法Java
做。有一些图书馆可以帮助序列化但为了满足基本需求,您通常会上课可序列化通过超载插入 and 萃取像这样的运算符:
class MyType
{
int value;
double factor;
std::string type;
public:
MyType()
: value(0), factor(0.0), type("none") {}
MyType(int value, double factor, const std::string& type)
: value(value), factor(factor), type(type) {}
// Serialized output
friend std::ostream& operator<<(std::ostream& os, const MyType& m)
{
return os << m.value << ' ' << m.factor << ' ' << m.type;
}
// Serialized input
friend std::istream& operator>>(std::istream& is, MyType& m)
{
return is >> m.value >> m.factor >> m.type;
}
};
int main()
{
std::vector<MyType> v {{1, 2.7, "one"}, {4, 5.1, "two"}, {3, 0.6, "three"}};
std::cout << "Serialize to standard output." << '\n';
for(auto const& m: v)
std::cout << m << '\n';
std::cout << "\nSerialize to a string." << '\n';
std::stringstream ss;
for(auto const& m: v)
ss << m << '\n';
std::cout << ss.str() << '\n';
std::cout << "Deserialize from a string." << '\n';
std::vector<MyType> v2;
MyType m;
while(ss >> m)
v2.push_back(m);
for(auto const& m: v2)
std::cout << m << '\n';
}
Output:
Serialize to standard output.
1 2.7 one
4 5.1 two
3 0.6 three
Serialize to a string.
1 2.7 one
4 5.1 two
3 0.6 three
Deserialize from a string.
1 2.7 one
4 5.1 two
3 0.6 three
The 序列化格式完全取决于程序员,您有责任确保您想要的类的每个成员连载是它本身可序列化(有一个插入/萃取运算符定义)。您还必须处理字段如何分隔(空格或换行符或零终止?)。
所有基本类型都有序列化 (插入/萃取) 运算符是预定义的,但您仍然需要小心诸如std::string
可以包含(例如)空格或换行符(如果您使用空格或换行符作为字段分隔符)。