C ++ MFC Serializre(CArchive&amp; ar),CArray <class *,class * =“”> </class *,>

时间:2014-10-20 02:05:24

标签: c++ arrays visual-c++ serialization mfc

我有一个程序,绘制形状:菱形,方形,矩形,直线,圆形......它与Microsoft中的相同。 我的问题是使用Serialize(CArchive&amp;)保存并加载文件,但是在使用CArray时我无法保存和加载文件。我怎么能这样做:

class BaseShape : public CObject
{
    DECLARE_SERIAL(BaseShape)
public:
    CPoint topLeft, bottomRight;
    COLORREF m_clrBack;
    EShapeType m_ShapeType;  //enum type of shape
public:
    BaseShape(void);  //empty method
    BaseShape (CPoint , CPoint, COLORREF, EShapeType);
    ~BaseShape(void);
    virtual void DrawShape (CDC*);  //empty method
    void Serialize(CArchive& ar);
};

实现BaseShape类的Serialize(CArchive&amp; ar):

IMPLEMENT_SERIAL(BaseShape, CObject, 1)
void BaseShape::Serialize(CArchive& ar)
    {
        if (ar.IsStoring())
        {
            ar << topLeft << bottomRight << m_clrBack << m_ShapeType;
        }
        else
        {
            int temp_shape;
            ar >> topLeft >> bottomRight >> m_clrBack >> temp_shape;
            m_ShapeType = (EShapeType)temp_shape;
        }
    }

Square类和Lozenge类由BaseShape派生:

class CSquare : public BaseShape
{
public:
    CSquare(void);
    CSquare (CPoint , CPoint, COLORREF, EShapeType);
    ~CSquare(void);
    void DrawShape(CDC*);
};

在MFC Document类中,我有:

//declare properties
  CArray<BaseShape*, BaseShape*> m_arrShape;
        COLORREF m_clrBack;
        EShapeType m_ShapeType;

//implement method

void CdemoDoc::Serialize(CArchive& ar)
{
    if (ar.IsStoring())
    {
        int i;
        ar << m_arrShape.GetSize();
        for (i = 0; i <m_arrShape.GetSize(); i++)
            ar << m_arrShape[i];
    }
    else
    {
        int ncount, i;
        ar >> ncount;
        m_arrShape.RemoveAll();
        for (i = 0; i < ncount; i++)
        {
            BaseShape* pShape = new BaseShape();
            ar >> pShape;
            m_arrShape.Add(pShape);
        }

在我的代码之上,当我点击打开文件时,形状没有显示,之前画了,虽然我的代码没有错误,我保存数据文件不成功。我不明白&#34; isloading()&#34;的代码行怎么样?功能工作。还有另一种方法吗?这是我所有项目的源代码:http://www.mediafire.com/download/jy23ct28bgqybdc/demo.rar

1 个答案:

答案 0 :(得分:1)

原因很简单:你不能创建一个BaseShape对象,并期望它在加载时变得专业化。

诀窍是ar&lt;&lt;保存完整的对象类型并将流的类名保存到。您只需要再次将流加载到对象指针中。 CArchive代码将尝试查找匹配的对象类来创建它并加载它。

请阅读MSDN about CObject serializing ...以及Scribble样本和其他内容。

if (ar.IsStoring())
{
  int i;
  ar << m_arrShape.GetSize();
  for (i = 0; i <m_arrShape.GetSize(); i++)
    ar << m_arrShape[i];
}
else
{
  int ncount, i;
  ar >> ncount;
  m_arrShape.RemoveAll();
  for (i = 0; i < ncount; i++)
  {
    BaseShape *pNewShape;
    ar >> pNewShape;
    m_arrShape.Add(pNewShape);
  }
}

PS:如果您提供示例代码,它应与您问题中的代码匹配。