MFC学习笔记(三)

来源:互联网 发布:linux系统移植是干嘛的 编辑:程序博客网 时间:2024/05/17 05:16

案例6: 数据保存与读取

修改代码:

修改文档类:

class CMyDoc : public CDocument

{

protected: // create from serialization only

CMyDoc();

DECLARE_DYNCREATE(CMyDoc)

 

// Attributes

public:

CRect m_rectA[MAX];

int   m_Count;

 

修改文档类的OnNewDocument函数:

BOOL CMyDoc::OnNewDocument()

{

if (!CDocument::OnNewDocument())

return FALSE;

    m_Count = 0;

// TODO: add reinitialization code here

// (SDI documents will reuse this document)

return TRUE;

}

void CMyDoc::Serialize(CArchive& ar)

{

if(ar.IsStoring())

{

ar << m_Count;

for(int i=0; i<m_Count; i++)

ar << m_rectA[i];

}

else

{

ar >> m_Count;

for(int i=0; i<m_Count; i++)

ar >> m_rectA[i];

}

}

 

 

修改视图类的OnDraw函数:

void CMyView::OnDraw(CDC* pDC)

{

CMyDoc* pDoc = GetDocument();

ASSERT_VALID(pDoc);

// TODO: add draw code for native data here

for(int i=0; i<pDoc->m_Count; i++)

pDC->Ellipse(pDoc->m_rectA[i]);

}

 

 

 

void CMyView::OnLButtonDown(UINT nFlags, CPoint point) 

{

// TODO: Add your message handler code here and/or call default

CMyDoc* pDoc = GetDocument();  

ASSERT_VALID(pDoc);

if(pDoc->m_Count < MAX)

{

int r = rand()%50+10;

CRect rect(point.x-r, point.y-r, point.x+r, point.y+r);

pDoc->m_rectA[pDoc->m_Count] = rect;

pDoc->m_Count++;

pDoc->SetModifiedFlag(); // 设置修改标志

InvalidateRect(rect, FALSE);

}

CView::OnLButtonDown(nFlags, point);

}

 

知识点:

1.数据是在Document类中处理的,将要保存的数据在此类的头文件中声明(public),便于读取时其他类需要调用来还原现场;

2.Serialize(CArchive &ar):其中CArchive 用序列化的方式来保存文件,是CFile类的一个辅助类, Serialize(CArchive &ar)函数具有CArchive参数ar的特性,即读写对象数据;

3.CArchive对象中包括成员函数IsStoring(),当该函数返回值为TRUE,写入数据,否是读取数据,使用输出运算符(<<)将对象数据插入到CArchive对象中或使用输入运算符(>>)提取数据;

4.CMyDoc* pDoc = GetDocument():获取document类的指针,便于调用document类中定义的变量(修改数据);

5.ASSERT_VALID(*)是一个宏,如果该指针为空则弹出对话框并终止程序运行;

6.pDoc->SetModifiedFlag():括号内为TRUE(已修改,可缺省)或者FALSE(未修改),设置已修改的标志,可以确定文件是否修改,可以达到未修改不用保存的目的。

0 0
原创粉丝点击