我有两个类(class):产品和派生果汁。我需要为这些类实现MFC Serialazation。class Product : CObject{protected: DECLARE_SERIAL(Product) //IMPLEMENT_SERIAL(Product, CObject, 0) in .cpp CString name; int expiring; double price;public: Product(); ~Product(); virtual void input_data(); virtual void print_data(); virtual void Serialize(CArchive& archive) { CObject::Serialize(archive); if (archive.IsStoring()) archive << name << expiring << price; else archive >> name >> expiring >> price; };};class Juice : public Product{private: double volume; CString taste;public: Juice(); ~Juice(); void input_data() override; void print_data() override; void Serialize(CArchive& archive) override { Product::Serialize(archive); if (archive.IsStoring()) archive << volume << taste; else archive >> volume >> taste; }};为了存储这些类的对象,我有Stock类,该类具有Product类指针的容器。class Stock{private: vector<shared_ptr<Product>> stock;public: Stock(); ~Stock(); void Add(shared_ptr<Product> p); void Print(); bool Save(string fname); bool Load(string fname); void Clear();};在Save and Load方法中,我试图实现序列化(根据本主题C++ MFC Serialization中的讨论)。bool Stock::Save(string fname){ CFile out; if (!out.Open(fname.c_str(), CFile::modeWrite | CFile::modeCreate)) return false; CArchive ar(&out, CArchive::store); ar.WriteCount(stock.size()); for (auto it = stock.begin(); it != stock.end(); ++it) { (*it)->Serialize(ar); } ar.Close(); out.Close(); return true;}bool Stock::Load(string fname){ CFile in; if (!in.Open(fname.c_str(), CFile::modeRead)) return false; CArchive ar(&in, CArchive::load); int cnt = ar.ReadCount(); for (int i = 0; i < cnt; i++) { auto p = make_shared<Product>(); p->Serialize(ar); stock.push_back(p); } ar.Close(); in.Close(); return true;}现在我遇到了问题。从文件中读取对象时,果汁对象的读取方式类似于产品(没有体积 Ant 味觉字段)。 Juice之后对对象的读取从Juice的其余信息开始,因此我在Product的Serialaize方法中得到了CArchiveException。如果仅使用产品对象添加到库存,则一切正常。我有什么错误,应该怎么做才能正确实现MFC序列化? 最佳答案 库存:保存需要更改为:for (auto it = stock.begin(); it != stock.end(); ++it){ ar << (*it).get();}和库存::负载需要更改为:for (int i = 0; i < cnt; i++){ Product* obj = nullptr; ar >> obj; stock.emplace_back(obj);}当使用ar 作为引用,这是MFC序列化代码在CObArray内部的外观(基本上,如果仅粘在MFC上,则将使用 vector 而不是 vector )if (ar.IsStoring()){ ar.WriteCount(m_nSize); for (INT_PTR i = 0; i < m_nSize; i++) ar << m_pData[i];}else{ DWORD_PTR nOldSize = ar.ReadCount(); SetSize(nOldSize); for (INT_PTR i = 0; i < m_nSize; i++) ar >> m_pData[i];}
10-04 19:48