MFC Carray自定义类的序列化与反序列化

问题遇到的现象和发生背景

我定义了一个数据类MyClass,然后定义了一个Myclass的Carray链表装入MyClass的数据。在反序列化时,MyClass的csting 变量的值是乱码的。

用代码块功能插入代码,请勿粘贴截图

#include
#include 
class MyClass :public CObject
{
    DECLARE_SERIAL(MyClass);
public:
    MyClass();
    ~MyClass();
public:
    CString  s;
    int a;
private:

public:
    virtual void Serialize(CArchive& ar);
};
IMPLEMENT_SERIAL(MyClass, CObject, 1)
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
void MyClass::Serialize(CArchive& ar)
{
    CObject::Serialize(ar);
        if (ar.IsStoring())
    {    // storing code
        ar << s << a;
    }
    else
    {    // loading code
        ar >> s >> a;
    }
}

void DD()//反序列化
{
    CFile mfile;
    mfile.Open("d:/1.txt", CFile::modeRead);
    CArchive ar(&mfile, CArchive::load, 4096);
    CArray a;
    a.Serialize(ar);
    MyClass *b1=nullptr;
    b1 = &a.GetAt(0);
     AfxMessageBox(b1->s);
    ar.Close();    mfile.Close();
}
VOID WW() //序列化
{
    CFile mfile;
    mfile.Open("d:/1.txt", CFile::modeCreate | CFile::modeWrite);
    CArchive ar(&mfile, CArchive::store, 4096);
    CArray a;
    MyClass b1, b2;
    b1.a = 11;
    b1.s = _T("666");
    a.Add(b1);
    a.Serialize(ar);
    ar.Close();    mfile.Close();
}
int main()
{
    WW();//序列化
    DD();//反序列化
}

运行结果及报错内容

然后报错。

img

我的解答思路和尝试过的方法

后来我尝试,不继承自CObject。代码通过编译,但是在测试的时候反序列化的值是乱码。


#include
#include 
class MyClass
{
public:
    MyClass();
    ~MyClass();
public:
    CString  s;
    int a;
private:

};

MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}

void DD()//反序列化
{
    CFile mfile;
    mfile.Open("d:/1.txt", CFile::modeRead);
    CArchive ar(&mfile, CArchive::load, 4096);
    CArray a;
    a.Serialize(ar);
    MyClass *b1=nullptr;
    b1 = &a.GetAt(0);
     AfxMessageBox(b1->s);//【字符串是乱码,输出是乱码;int数值是没问题的。】
    ar.Close(); 
    mfile.Close();
}
VOID WW() //序列化
{
    CFile mfile;
    mfile.Open("d:/1.txt", CFile::modeCreate | CFile::modeWrite);
    CArchive ar(&mfile, CArchive::store, 4096);
    CArray a;
    MyClass b1, b2;
    b1.a = 11;
    b1.s = _T("666");
    a.Add(b1);
    a.Serialize(ar);
    ar.Close();    mfile.Close();
}
int main()
{
    WW();//序列化
    DD();//反序列化
}

我想要达到的结果

我的问题出在哪里?如何才能将CArray a;这个数组序正确的列化和反序列化?

错误的意思是你的MyClass类应该重载=操作符,不然序列化不知道如何进行MyClass对象的=操作
你加上=操作符重载函数看看

class MyClass :public CObject
{
    DECLARE_SERIAL(MyClass);
public:
    MyClass();
    ~MyClass();
    void operator = (const MyClass &my) { s = my.s;a = my.a;}
public:
    CString  s;
    int a;
private:
 
public:
    virtual void Serialize(CArchive& ar);
};
IMPLEMENT_SERIAL(MyClass, CObject, 1)
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
void MyClass::Serialize(CArchive& ar)
{
    CObject::Serialize(ar);
        if (ar.IsStoring())
    {    // storing code
        ar << s << a;
    }
    else
    {    // loading code
        ar >> s >> a;
    }
}