std :: stringstream 또는 boost :: lexical_cast와 같은 표준 기술을 사용하여 C++ 클래스를 직렬화하고 싶습니다.문자열 스트림 객체와 호환되는 C++ 클래스를 만드는 방법은 무엇입니까?
예를 들어 Point 객체 (2, 4)가있는 경우 "(2, 4)"로 직렬화하고이 문자열에서 Point 객체를 생성 할 수 있습니다.
이미 몇 가지 문제가 있지만 일부 코드가 있습니다. 문자열을 가리 키지 만 입력이 스트림에서 완전히 읽히지 않는 경우가 있습니다. 문자열을 포인트로 변환하면 bad_cast 예외가 발생합니다.
class Point
{
public:
Point() : mX(0), mY(0) {}
Point(int x, int y) : mX(x), mY(y){}
int x() const { return mX; }
int y() const { return mY; }
private:
int mX, mY;
};
std::istream& operator>>(std::istream& str, Point & outPoint)
{
std::string text;
str >> text; // doesn't always read the entire text
int x(0), y(0);
sscanf(text.c_str(), "(%d, %d)", &x, &y);
outPoint = Point(x, y);
return str;
}
std::ostream& operator<<(std::ostream& str, const Point & inPoint)
{
str << "(" << inPoint.x() << ", " << inPoint.y() << ")";
return str;
}
int main()
{
Point p(12, 14);
std::string ps = boost::lexical_cast<std::string>(p); // "(12, 14)" => OK
Point p2 = boost::lexical_cast<Point>(ps); // throws bad_cast exception!
return 0;
}
어떻게 이러한 문제를 해결할 수 있습니까?
고마워,이 간단한 변경 내 코드를 고정! – StackedCrooked