21.4.4 创建记录集视图(2)
这里的显式强制转换是必要的,因为转换是在类层次结构中从基类向派生类进行的。稍后即可实现其他两个重写的函数。
因为CCustomerSet对象是在堆上创建的,所以需要在CCustomerView类的析构函数中将其删除:
- CCustomerView::~CCustomerView()
- {
- if (m_pSet)
- delete m_pSet;
- }
CCustomerView类中的OnInitialUpdate()函数重写应该像前面看到的那样实现:
- void CCustomerView::OnInitialUpdate()
- {
- BeginWaitCursor();
- GetRecordset();
- CRecordView::OnInitialUpdate();
- if (m_pSet->IsOpen())
- {
- CString strTitle = m_pSet->m_pDatabase->GetDatabaseName();
- CString strTable = m_pSet->GetTableName();
- if(!strTable.IsEmpty())
- strTitle += _T(":") + strTable;
- GetDocument()->SetTitle(strTitle);
- }
- EndWaitCursor();
- }
CProductView类的定义与CCustomerView类几乎相同,主要区别在于与其相关的对话框窗体:
- // ProductView.h : header file
- #pragma once
-
- class CProductSet;
-
- class CProductView : public CRecordView
- {
- public:
- CProductView();
- virtual ~CProductView();
-
- public:
- enum { IDD = IDD_PRODUCT_FORM }; // Form Data
- CProductSet* m_pSet;
-
- // Operations
- public:
- CProductSet* GetRecordset();
-
- // Implementation
- protected:
- #ifdef _DEBUG
- virtual void AssertValid() const;
- virtual void Dump(CDumpContext& dc) const;
- #endif
- };
现在,可以使用为上一个类使用的方法,添加OnGetRecordset()、DoDataExchange()和OnInitialUpdate()函数的重写版本,并在ProductView.cpp文件的开始处添加下面的指令:
- #include "stdafx.h"
- #include "DBSimpleUpdate.h"
- #include "ProductView.h"
- #include "ProductSet.h"
构造函数应该初始化m_pSet成员,析构函数应该删除m_pSet指向的对象-- 因为该对象是在堆上创建的。构造函数和析构函数的定义如下:
- CProductView::CProductView()
- : CRecordView(CProductView::IDD),
- m_pSet(NULL)
- {
- }
-
- CProductView::~CProductView()
- {
- if (m_pSet)
- delete m_pSet;
- }
OnGetRecordset()函数的实现是:
- CRecordset* CProductView::OnGetRecordset()
- {
- if(m_pSet == NULL) // If there is no recordset
- {
- m_pSet = new CProductSet(NULL); // create one
- m_pSet->Open(); // then open it
- }
- return m_pSet; // Return the address of the recordset
- }
CProductView类中GetRecordset()函数的实现基本上也与CCustomerView类的情况相同:
- CProductSet* CProductView::GetRecordset()
- {
- return static_cast<CProductSet*>(OnGetRecordset());
- }
还可以添加将在调试模式中使用的诊断函数的定义:
- #ifdef _DEBUG
- void CProductView::AssertValid() const
- {
- CRecordView::AssertValid();
- }
-
- void CProductView::Dump(CDumpContext& dc) const
- {
- CRecordView::Dump(dc);
- }
- #endif //_DEBUG
我们将在本章稍后再返回到需要在CProductView类中实现的函数,在此期间可以给对话框添加所需要的控件。