我正在尝试序列化我班级的一些私人属性:
class Task {
public:
enum Status { COMPLETED, PENDIENT };
// BLAH BLAH BLAH
// CLASS GETTERS SETTERS ETC...
const std::fstream serializeObject( std::fstream &stream );
private:
void setID();
static int sCount;
int id;
std::string text;
Status status;
tm timestamp;
};
serializeObject的定义如下:
const std::fstream Task::serializeObject( std::fstream &stream ) {
stream.write((char *) &id, sizeof(int));
stream.write((char *) &text, sizeof(std::string));
stream.write((char *) &status, sizeof(Status));
stream.write((char *) ×tamp, sizeof(tm));
return stream;
}
GCC会返回很多错误:
In file included from /usr/include/c++/4.4/ios:39,
from /usr/include/c++/4.4/ostream:40,
from /usr/include/c++/4.4/iostream:40,
from task.cpp:1:
/usr/include/c++/4.4/bits/ios_base.h: In copy constructor ‘std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’:
/usr/include/c++/4.4/bits/ios_base.h:790: error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private
/usr/include/c++/4.4/iosfwd:47: error: within this context
/usr/include/c++/4.4/iosfwd: In copy constructor ‘std::basic_fstream<char, std::char_traits<char> >::basic_fstream(const std::basic_fstream<char, std::char_traits<char> >&)’:
/usr/include/c++/4.4/iosfwd:87: note: synthesized method ‘std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’ first required here
/usr/include/c++/4.4/streambuf: In copy constructor ‘std::basic_filebuf<char, std::char_traits<char> >::basic_filebuf(const std::basic_filebuf<char, std::char_traits<char> >&)’:
/usr/include/c++/4.4/streambuf:770: error: ‘std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char, _Traits = std::char_traits<char>]’ is private
/usr/include/c++/4.4/iosfwd:78: error: within this context
/usr/include/c++/4.4/iosfwd: In copy constructor ‘std::basic_fstream<char, std::char_traits<char> >::basic_fstream(const std::basic_fstream<char, std::char_traits<char> >&)’:
/usr/include/c++/4.4/iosfwd:87: note: synthesized method ‘std::basic_filebuf<char, std::char_traits<char> >::basic_filebuf(const std::basic_filebuf<char, std::char_traits<char> >&)’ first required here
task.cpp: In member function ‘std::fstream Task::serializeObject(std::fstream&)’:
task.cpp:104: note: synthesized method ‘std::basic_fstream<char, std::char_traits<char> >::basic_fstream(const std::basic_fstream<char, std::char_traits<char> >&)’ first required here
我做错了什么?我跟随this示例。复制了商店功能并调整了一下。
答案 0 :(得分:3)
Task::serializeObject()
的返回值是fstream
,而不是fstream&
:这是尝试制作stream
的副本,而流是不可复制的。来自std::ios_base::ios_base
:
删除复制构造:stream不可复制
更改为:
std::fstream& Task::serializeObject( std::fstream &stream )
注意我放弃了const
因为我不确定为什么要这样做。
另外,这个:
stream.write((char *) &text, sizeof(std::string));
不会按你的想法行事。 std::string
将包含指向实际数据的指针,并且使用此实际数据不会写入stream
。使用std::string::c_str()
,可能使用std::string::length()
,以便在重新阅读时知道字符串的长度。