17.3.3 序列化元素类(2)

2013-10-07 16:13:04 · 作者: · 浏览: 70

17.3.3  序列化元素类(2)

这个函数的形式和CSketcherDoc类中提供的函数一样。重载的析取和插入运算符支持在CElement中定义的所有数据成员,所以所有操作都是由这些运算符完成的。注意必须调用CObject类的Serialize()成员,以确保可以序列化继承的数据成员。

对于CLine类,可以把这个函数编写为:

  1. void CLine::Serialize(CArchive& ar)  
  2. {  
  3. CElement::Serialize(ar);                                                    // Call the base class function  
  4. if (ar.IsStoring())  
  5. { // Writing to the file  
  6. ar << m_EndPoint;                                                               // The end point  
  7. }  
  8. else  
  9. { // Reading from the file  
  10. ar >> m_EndPoint;                                                               // The end point  
  11. }  
  12. }  

CArchive对象ar的析取和插入运算符支持所有数据成员。其中调用基类CElement的Serialize()成员序列化其数据成员,而这将调用CObject的Serialize()成员。可以看到序列化过程在这个类层次结构中是如何层叠的。

CRectangle类的Serialize()函数成员比较简单:

  1. void CRectangle::Serialize(CArchive& ar)  
  2. {  
  3. CElement::Serialize(ar);                                            // Call the base class function  
  4. if (ar.IsStoring())  
  5. { // Writing to the file  
  6. ar << m_BottomRight;                                                    // Bottom-right point for the rectangle  
  7. }  
  8. else  
  9. { // Reading from the file  
  10. ar >> m_BottomRight;  
  11. }  
  12. }  

这只调用直接基类函数Serialize(),序列化矩形的右下角点。

CCircle类的Serialize()函数也与CRectangle类相同:
 

  1. void CCircle::Serialize(CArchive& ar)  
  2. {  
  3. CElement::Serialize(ar);                                        // Call the base class function  
  4. if (ar.IsStoring())  
  5. {   // Writing to the file  
  6. ar << m_BottomRight;                                                // Bottom-right point for the circle  
  7. }  
  8. else  
  9. { // Reading from the file  
  10. ar >> m_BottomRight;  
  11. }  
  12. }  

对于CCurce类,要做的工作就比较多。CCurve类使用vector<CPoint>容器存储定义的点,因为这不能直接序列化,所以您必须自己负责处理。将文档序列化之后,情况就不太难了。可以如下面这样编写Serialize()函数的代码:
 

  1. void CCurve::Serialize(CArchive& ar)  
  2. {  
  3. CElement::Serialize(ar);                                    // Call the base class function  
  4. // Serialize the vector of points  
  5. if (ar.IsStoring())  
  6. {  
  7. ar << m_Points.size();                                      // Store the point count  
  8. // Now store the points  
  9. for(size_t i = 0 ; i< m_Points.size() ; ++i)  
  10. ar << m_Points[i];  
  11. }  
  12. else  
  13. {  
  14. size_t nPoints(0);                                              // Stores number of points  
  15. ar >> nPoints;                                                          // Retrieve the number of points  
  16. // Now retrieve the points  
  17. CPoint point;  
  18. for(size_t i = 0 ; i < nPoints ; ++i)  
  19. {  
  20. ar >> point;  
  21. m_Points.push_back(point);  
  22. }  
  23. }  
  24. }