我可以重载CArchive<<操作符使用std :: string? [英] Can I overload CArchive << operator to work with std::string?
问题描述
我在我的MFC应用程序中使用std :: string,我想将其存储在doc的Serialize()函数。我不想将它们存储为CString因为它写入自己的东西在那里,我的目标是创建一个文件,我知道的格式,并可以由其他应用程序读取,而不需要CString。所以我想存储我的std ::字符串为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;
}
}
上面的代码不是很好,一个temp bfr来读取字符串。首先我可以读取字符串直接到std :: string没有临时缓冲区?其次,我可以重载<<缓冲区为std :: string / CArchive所以我可以简单地使用ar< theString?总之,有一个更好的方法来读/写std :: string使用CArchive对象?
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?
推荐答案
你可以构建一个内部CString你的stl字符串并序列化。例如:
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<<操作符使用std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!