When creating a class in C++ that will hold data for an application
CObject
Serialize
method
afxtempl.h
in the stdafx.h
file
CArray
of this class
global
method for serializing elements in the
CArray
.
Serialize
method of the class from the
Serialize
method of the Document.
In order to use the template classes like CArray
, it is necessary
to add the following line at the end of the stdafx.h
file
#include <afxtempl.h>
Here is an example of a header file: data.h
class CData: public CObject { DECLARE_SERIAL(CData) public: CData(); virtual ~CData(); const CData& operator=(const CData& data); CData(const CData& data); void Serialize(CArchive &ar); public: int m_nAge; double m_dGPA; }; template <> void AFXAPI SerializeElements <CData> ( CArchive& ar, CData* pData, INT_PTR nCount ); typedef CArray<CData, CData&> CDataArray;
Here is the corresponding implementation: data.cpp
IMPLEMENT_SERIAL(CData, CObject, 0) CData::CData() { m_nAge = 18; m_dGPA = 2.0; } CData::~CData() { } const CData& CData::operator=(const CData& data) { m_nAge = data.m_nAge; m_dGPA = data.m_dGPA; return *this; } CData::CData(const CData& data) { *this = data; } void CData::Serialize(CArchive &ar) { if (ar.IsStoring()) { ar << m_nAge << m_dGPA; } else { ar >> m_nAge >> m_dGPA; } } template <> void AFXAPI SerializeElements <CData> ( CArchive& ar, CData* pData, INT_PTR nCount ) { for ( int i = 0; i < nCount; i++, pData++ ) { // Serialize each CData object pData->Serialize( ar ); } }