这里以 MFC 为例,标准 C++ 同样适用,替换成相应的 std::iostream 即可。
class MydataBaseHardware {
public:
int d;
};
CArchive& operator<<( CArchive& ar, MydataBaseHardware& data)
{
return ar << (WORD)data.d;
}
CArchive& operator>>( CArchive& ar, MydataBaseHardware& data)
{
WORD d;
ar >> d;
data.d = d;
return ar;
}
class MydataBase : public MydataBaseHardware{};
CArchive& operator<<( CArchive& ar, MydataBase& data)
{
return ar << data.d;
}
CArchive& operator>>( CArchive& ar, MydataBase& data)
{
return ar >> data.d;
}
class MydataHardware {
public:
int a;
int b;
int c;
MydataBase base;
};
CArchive& operator<<( CArchive& ar, MydataHardware& data)
{
return ar << (WORD)data.a << (WORD)data.b << (WORD)data.c << (MydataBaseHardware)data.base;
}
CArchive& operator>>( CArchive& ar, MydataHardware& data)
{
WORD a, b, c;
ar >> a >> b >> c;
data.a = a;
data.b = b;
data.c = c;
ar >> (MydataBaseHardware)data.base;
return ar;
}
class Mydata : public MydataHardware{};
CArchive& operator<<( CArchive& ar, Mydata& data)
{
return ar << data.a << data.b << data.c << data.base;
}
CArchive& operator>>( CArchive& ar, Mydata& data)
{
return ar >> data.a >> data.b >> data.c >> data.base;
}
void CMyDoc::Serialize(CArchive& ar)
{
Mydata data;
MydataHardware& hd = data;
if (ar.IsStoring())
{
// TODO: add storing code here
ar << hd;
}
else
{
// TODO: add loading code here
ar >> hd;
}
}