这些是这些函数的原型。
这是成员功能:
virtual void write(std::ostream& os) const;
这个是免费功能:
std::ostream& operator<<(std::ostream& os, const Text& text);
我实现这两个功能:
void Text::write(std::ostream& os) const
{
if (m_content != nullptr)
{
os << m_content;
}
}
std::ostream& operator<<(std::ostream& os, const Text& text)
{
return text.write(os);
}
我的问题是我得到了这个错误:
C++ initial value of reference to non-const must be an lvalue
我确信我做的每件事都是对的。
正如Scheff在注释中所指出的,您需要从Text::write
:返回os
std::ostream& Text::write(std::ostream& os) const
{
if (m_content != nullptr)
{
os << m_content;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const Text& text)
{
return text.write(os);
}