获取错误:引用非常数的初始值必须是左值

  • 本文关键字:取错误 引用 非常 获取 c++
  • 更新时间 :
  • 英文 :


这些是这些函数的原型。

这是成员功能:

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);
}

最新更新