visual-c++serializationmfccarchive

CArchive serialization with operators << >> no operator found which takes a left-hand of type cArchive


Following this tutorial, http://msdn.microsoft.com/en-us/library/vstudio/3bfsbt0t.aspx I implement this code:

class Esame: public CObject
{

public:

INT voto;
INT crediti;
BOOL lode;
CString nome;
Esame(){}
Esame(CString nome, INT voto, BOOL lode, INT crediti) :nome(nome), voto(voto), lode    (lode), crediti(crediti) {}

void Serialize(CArchive& ar);

protected:
DECLARE_SERIAL(Esame)
};

IMPLEMENT_SERIAL(Esame, CObject, 1)

void Esame::Serialize(CArchive& ar){
CObject::Serialize(ar);
if (ar.IsStoring())
{       
    ar << voto << lode << crediti;
}
else
{       
    ar >> voto >> lode >> crediti;
}
}

then I call:

CFile file(_T("file.and"), CFile::modeCreate);
CArchive afr(&file, CArchive::store);
Esame e;
afr << e;

but i get << operator no operator found which takes a left-hand of type cArchive


Solution

  • That's because you didn't provide an overload of operator<< for your class Esame. The article you linked to doesn't do this either, so perhaps you intended to do this instead:

    CFile file(_T("file.and"), CFile::modeCreate);
    CArchive afr(&file, CArchive::store);
    Esame e;
    e.Serialize(ar);
    

    So, you call the Serialize function directly, and the implementation in your class uses operator<< to serialize the required primitive member variables and calls Serialize on other complex objects.

    As the tutorial shows:

    void CCompoundObject::Serialize( CArchive& ar )
    {
       CObject::Serialize( ar );    // Always call base class Serialize.
       m_myob.Serialize( ar );    // Call Serialize on embedded member.
       m_pOther->Serialize( ar );    // Call Serialize on objects of known exact type. 
    
       // Serialize dynamic members and other raw data 
       if ( ar.IsStoring() )
       {
          ar << m_pObDyn;
          // Store other members
       }
       else
       {
          ar >> m_pObDyn; // Polymorphic reconstruction of persistent object  
          //load other members
       }
    }