Point - worked example
key : purple - original code / blue - new code
Step 1 :
Continue with the same project as used for the previous task (creating an extra view). Again it is suggested that a copy should be taken of this previous program and that the following steps should be followed.
Step 2 :
Create a new class, call it CName. The specified type should be Generic and it should inherit from the CObject base class.
Step 3 :
Add the following member variables to the class (private access) :
CString m_strFirstName;
CString m_strSecondName;
Step 4 :
Pass the variables through the new class's constructor. Add the following code to the header file :
CName(const CString &strFirstName, const CString &strSecondName);
And the following code to the source file :
CName::CName(const
CString &strFirstName, const CString &strSecondName)
{
m_strFirstName = strFirstName;
m_strSecondName = strSecondName;
}
Step 5 :
Add the following Get functions to allow data retrieval :
CString
CName::GetFullName()
{
return m_strFirstName + " " + m_strSecondName;
}
CString
CName::GetFirstName()
{
return m_strFirstName;
}
CString
CName::GetSecondName()
{
return m_strSecondName;
}
Step 6 :
Add the following pointer to the Document (private access) :
CName* m_pName;
And inform the Document about the new class :
#include "Name.h"
Step 7 :
Edit the AddNames() function in the Document :
void
CNamesDoc::AddNames()
{
CEnterNamesDlg dlg;
if(dlg.DoModal() == IDOK)
{
CName * pName = new CName(dlg.m_strFirstName, dlg.m_strSecondName);
m_pName = pName;
UpdateAllViews( NULL );
}
}
Step 8 :
Edit the Get functions in the Document :
CString
CNamesDoc::GetFirstName()
{
if(m_pName)
{return m_pName->GetFirstName();
}
else
{return " ";
}
}
CString
CNamesDoc::GetSecondName()
{
if(m_pName)
{return m_pName->GetSecondName();
}
else
{return " ";
}
}
CString
CNamesDoc::GetFullName()
{
if(m_pName)
{return m_pName->GetFullName();
}
else{return " ";
}
}
Step 9 :
Add the following code to the Document's constructor and destructor :
CNamesDoc::CNamesDoc()
{
m_strFirstName = "";
m_strSecondName = "";
m_pName = NULL;
}
CNamesDoc::~CNamesDoc()
{
if(m_pName != NULL)
{delete m_pName;
}
}
Step 10 :
Add the following code to the OnDraw() function in the View class :
void
CNamesView::OnDraw(CDC* pDC)
{
CNamesDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
pDC->TextOut(0, 0, pDoc->GetFullName() );
}
Click here for the basic exercise
Click here for the source code
Click here to return to menu