概述
通过ostream/istream完成数据序列化,简单直接,学到此,做个记录。
std::ostream& operator<<(std::ostream& o, const Point& p) {
o << p.x << " " << p.y << " ";
return o;
}
std::istream& operator>>(std::istream& is, Point& p) {
is >> p.x;
is >> p.y;
return is;
}
std::ostream& operator<<(std::ostream& o, const Paths& paths) {
o << paths.source << paths.destinations.size() << " ";
for (const auto& x : paths.destinations) {
o << x;
}
return o;
}
std::istream& operator>>(std::istream& is, Paths& paths) {
size_t size;
is >> paths.source;
is >> size;
for (;size;size--) {
Point tmp;
is >> tmp;
paths.destinations.push_back(tmp);
}
return is;
}
测试代码
#include <iostream