我有一个程序,绘制形状:菱形,正方形,矩形,直线,圆圈.微软的油漆是一样的。我的问题是使用序列化(CArchive &)保存和加载文件,但在使用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类的序列化(CArchive& 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;
}
}正方形类和菱形类是由BaseShape导出的:
class CSquare : public BaseShape
{
public:
CSquare(void);
CSquare (CPoint , CPoint, COLORREF, EShapeType);
~CSquare(void);
void DrawShape(CDC*);
};在MFC文档类中,我有:
//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);
}在我的代码,上,当我单击打开文件时,没有显示形状,这是以前绘制的,虽然我的代码不是错误,但我成功地保存了不确定的数据文件。我不明白"isloading()“函数的代码行是如何工作的。还有别的办法吗?这是我所有项目的源代码:http://www.mediafire.com/download/jy23ct28bgqybdc/demo.rar
发布于 2014-10-20 09:50:36
原因很简单:您不能创建一个BaseShape对象,并且期望它在加载时得到专门化。
诀窍是ar <<保存完整的对象类型,并将流中的类名保存到。您只需要再次将流加载到对象指针中。CArchive代码将试图找到匹配的对象类,创建它并加载它。
请阅读关于CObject序列化的MSDN..。也包括拼字样本和其他样本。
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:如果您提供示例代码,它应该与您问题中的代码相匹配。
https://stackoverflow.com/questions/26457591
复制相似问题