2013-11-26 28 views
0

按照本教程中,http://msdn.microsoft.com/en-us/library/vstudio/3bfsbt0t.aspx我實現這個代碼:與運營商<< > CArchive的序列化>沒有操作員發現這需要類型的左手的CArchive

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; 
} 
} 

然後我打電話:

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

但我得到 < <操作員找不到操作員找到哪個類型需要左手存檔

回答

1

這是因爲您沒有爲您的課程Esame提供operator<<的超載。您鏈接到不這樣做無論是文章,那麼也許你打算這樣做,而不是:

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

所以,你直接調用Serialize功能,在你的類實現使用operator<<序列化所需的原成員變量並在其他複雜對象上調用Serialize

作爲教程顯示:

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 
    } 
} 
+0

好,但是我失去了使用CArchive的「舒適性」:我可以簡單地重載<< and >>作爲任何祖先類; CArchive的幫助(我相信)會自動執行運算符的重載(我認爲這是通過DECLARE_SERIAL和IMPLEMENT_SERIAL宏完成的)。手動超載<< >>通常是系統 – volperossa

0
afr << &e; 

指針類型需要的。

相關問題