我可以重载CArchive吗<<运算符与 std::string 一起使用? [英] Can I overload CArchive << operator to work with std::string?

查看:34
本文介绍了我可以重载CArchive吗<<运算符与 std::string 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 MFC 应用程序中使用 std::string,我想将它存储在 doc 的 Serialize() 函数中.我不想将它们存储为 CString,因为它会在其中写入自己的内容,而我的目标是创建一个我知道其格式并且可以被其他应用程序读取而无需 CString 的文件.所以我想将我的 std::strings 存储为 4 字节(int)字符串长度,后跟包含该字符串的大小的缓冲区.

I am using std::string in my MFC application and I want to store it in doc's Serialize() function. I don't want to store them as CString because it writes its own stuff in there and my goal is to create a file that I know the format of and can be read by other application without needing CString. So I would like to store my std::strings as 4 bytes (int) string length followed by buffer of that size containing the string.

void CMyDoc::Serialize(CArchive& ar)
{
    std::string theString;

    if (ar.IsStoring())
    {
        // TODO: add storing code here
        int size = theString.size();
        ar << size;
        ar.Write( theString.c_str(), size );

    }
    else
    {
        // TODO: add loading code here
        int size = 0;
        ar >> size;
        char * bfr = new char[ size ];
        ar.Read( bfr, size);
        theString = bfr;
        delete [] bfr;
    }
}

上面的代码不是很好,我必须分配一个临时 bfr 来读取字符串.首先,我可以在没有临时缓冲区的情况下将字符串直接读入 std::string 吗?其次,我可以超载 <<std::string/CArchive 的缓冲区,所以我可以简单地使用 ar <<字符串?总的来说,有没有更好的方法来使用 CArchive 对象读/写 std::string?

The above code is not great and I have to allocate a temp bfr to read the string. First can I read the string directly into std::string without the temp buffer? Secondly can I overload the << buffer for std::string / CArchive so I can simply use ar << theString? Overall is there a better way to read/write std::string using CArchive object?

推荐答案

您可以从您的 stl 字符串构建一个就地 CString 并将其序列化.类似的东西:

You could build an inplace CString from your stl string and serialize that. Something like:

CString c_string(my_stl_string.c_str();
ar << c_string;

你可以把它放在一个全局操作符重载中,这样你就可以了

You could put this in a global operater overload so it can you can just

ar << my_c_string;

来自任何地方,例如:

CArchive& operator<<(CArchive rhs, string lhs) {
    CString c_string(lhs.c_str());
    rhs << c_string;
}

这篇关于我可以重载CArchive吗&lt;&lt;运算符与 std::string 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆