1.在类中添加
.h文件中:
注释//DECLARE_DYNAMIC(MyClass)
添加DECLARE_SERIAL(MyClass)
添加方法void Serialize(CArchive& ar);
1 class MyClass: public CObject 2 { 3 //DECLARE_DYNAMIC(MyClass) 4 public: 5 DECLARE_SERIAL(MyClass) 6 MyClass(); 7 ~MyClass(); 8 void Serialize(CArchive& ar); 9 protected: 10 //变量方法; 11 private: 12 //变量方法; 13 };
.cpp文件中
//IMPLEMENT_DYNAMIC(MyClass, CWnd)
IMPLEMENT_SERIAL(MyClass,CObject,1)
并实现方法void Serialize(CArchive& ar);
1 #include "MyClass.h" 2 //IMPLEMENT_DYNAMIC(MyClass, CWnd) 3 4 IMPLEMENT_SERIAL(MyClass,CObject,1) 5 6 MyClass::MyClass(){...} 7 8 void MyClass::Serialize(CArchive& ar) 9 { 10 if (ar.IsStoring()) 11 { 12 ar<<变量<<变量; 13 } 14 else 15 { 16 ar>>变量>>变量; 17 } 18 }
2.读写操作
1 //写入: 2 3 CFile file( "c:\\aa.dat ", CFile::modeCreate | CFile::modeWrite); 4 CArchive ac(&file, CArchive::store); 5 myClass.Serialize(ar); 6 7 //读取: 8 9 CFile file( "c:\\aa.dat ", CFile::modeRead); 10 CArchive ac(&file, CArchive::load); 11 MyClass myClass = new MyClass(); 12 myClass.Serialize(ar); 13 CString s; 14 s.Format( "%d ", n); 15 MessageBox(s);
3.也可以参考
http://www.cnblogs.com/ylhome/archive/2010/03/15/1686558.html
不过我怎么就不能使用<<与>> 这两个流操作符呢?
下次不加行号了!
完全没有异常处理,有待添加!