我正在尝试创建一个名为Serializable的基类,以形式化一些(反)序列化。但是我为下面的代码得到了非常神秘的错误(在http://goo.gl/v92vmb现场运行)。我用gd = c ++ 11和clang ++尝试了g ++ - 4.9,但没有取得更多成功。
有谁可以告诉我什么是错的,也许可以改善这种情况?
#include <iostream>
#include <sstream>
/** Classes inheriting this class must implement the serialize-function...*/
class Serializable {
public:
virtual void serialize(std::ostream& os) const = 0;
virtual void deserialize(std::istream& is) const = 0;
};
std::ostream& operator<< (std::ostream& os, const Serializable& s) {
s.serialize(os);
return os;
}
std::istream& operator>> (std::istream& is, const Serializable& s) {
s.deserialize(is);
return is;
}
class Foo : public Serializable {
public:
int N;
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) const override;
};
void Foo::serialize(std::ostream& os) const {
os << N;
}
void Foo::deserialize(std::istream& is) const {
is >> N;
std::cout << "Got " << N << std::endl;
}
int main()
{
std::stringstream ss;
ss << "9";
Foo f;
f.deserialize(ss);
return 0;
}
错误:
In member function 'virtual void Foo::deserialize(std::istream&)
const':
main.cpp:32:11: error: cannot bind 'std::istream {aka std::basic_istream<ch
ar>}' lvalue to 'std::basic_istream<char>&&'
is >> N;
^
In file included from /usr/include/c++/4.8.3/iostream:40:0,
from main.cpp:1:
/usr/include/c++/4.8.3/istream:872:5: error: initializing argument 1 of '
std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_Ch
arT, _Traits>&&, _Tp&) [with _CharT = char; _Traits = std::char_traits<char
>; _Tp = const int]'
operator>>(basic_istream<_CharT, _Traits>&& __is, _Tp& __x)
答案 0 :(得分:2)
好的,正如@lisyarus所见,deserialize方法被声明为const。删除它解决了问题。如果只有错误消息更清楚。