17.3.3 序列化元素类(2)
这个函数的形式和CSketcherDoc类中提供的函数一样。重载的析取和插入运算符支持在CElement中定义的所有数据成员,所以所有操作都是由这些运算符完成的。注意必须调用CObject类的Serialize()成员,以确保可以序列化继承的数据成员。
对于CLine类,可以把这个函数编写为:
- void CLine::Serialize(CArchive& ar)
- {
- CElement::Serialize(ar); // Call the base class function
- if (ar.IsStoring())
- { // Writing to the file
- ar << m_EndPoint; // The end point
- }
- else
- { // Reading from the file
- ar >> m_EndPoint; // The end point
- }
- }
CArchive对象ar的析取和插入运算符支持所有数据成员。其中调用基类CElement的Serialize()成员序列化其数据成员,而这将调用CObject的Serialize()成员。可以看到序列化过程在这个类层次结构中是如何层叠的。
CRectangle类的Serialize()函数成员比较简单:
- void CRectangle::Serialize(CArchive& ar)
- {
- CElement::Serialize(ar); // Call the base class function
- if (ar.IsStoring())
- { // Writing to the file
- ar << m_BottomRight; // Bottom-right point for the rectangle
- }
- else
- { // Reading from the file
- ar >> m_BottomRight;
- }
- }
这只调用直接基类函数Serialize(),序列化矩形的右下角点。
CCircle类的Serialize()函数也与CRectangle类相同:
- void CCircle::Serialize(CArchive& ar)
- {
- CElement::Serialize(ar); // Call the base class function
- if (ar.IsStoring())
- { // Writing to the file
- ar << m_BottomRight; // Bottom-right point for the circle
- }
- else
- { // Reading from the file
- ar >> m_BottomRight;
- }
- }
对于CCurce类,要做的工作就比较多。CCurve类使用vector<CPoint>容器存储定义的点,因为这不能直接序列化,所以您必须自己负责处理。将文档序列化之后,情况就不太难了。可以如下面这样编写Serialize()函数的代码:
- void CCurve::Serialize(CArchive& ar)
- {
- CElement::Serialize(ar); // Call the base class function
- // Serialize the vector of points
- if (ar.IsStoring())
- {
- ar << m_Points.size(); // Store the point count
- // Now store the points
- for(size_t i = 0 ; i< m_Points.size() ; ++i)
- ar << m_Points[i];
- }
- else
- {
- size_t nPoints(0); // Stores number of points
- ar >> nPoints; // Retrieve the number of points
- // Now retrieve the points
- CPoint point;
- for(size_t i = 0 ; i < nPoints ; ++i)
- {
- ar >> point;
- m_Points.push_back(point);
- }
- }
- }