错误:无法将'std :: ostream {aka std :: basic_ostream <char>}'左值绑定到'std :: basic_ostream <char>&amp;&amp;'

时间:2017-01-18 22:19:46

标签: c++ c++11

你好everonye甚至我在这里找到了许多关于这个问题的答案,我根本无法解释为什么事情无法解决它尝试一切。

所以我的问题是当我尝试实现operator&lt;&lt;时,我有一个名为Matrix的类。作为内联方法我得到以下错误

 error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’

以下是我的方法的实现在类

中的实现方式
 ostream& operator<<(ostream& out)
{

    for (int i = 0; i < this->getHeight(); ++i) {
        for (int j = 0; j < this->getWidth(); ++j) {

            out << this->(i, j) << "\t";
        }
        out<< "\n";
    }

    return out;
}

当我按照这样的功能实现它时

    template <typename U>
ostream& operator<<(ostream& out, const Matrix<U>& c)
{

    for (int i = 0; i < c.getHeight(); ++i) {
        for (int j = 0; j < c.getWidth(); ++j) {

            out << c(i, j) << "\t";
        }
        out << "\n";
    }

    return out;
} 

它有效:( 任何人都可以解释我在这里做错了什么

1 个答案:

答案 0 :(得分:1)

std::ostream& Matrix<U>::operator <<(std::ostream&)具有等效的自由功能签名std::ostream& operator <<(Matrix<U>&, ostream&) 您想要的(出于多种原因)。

无法将流operator <<operator >>实现为UDT的成员函数,因为第一个参数必须始终是流。您可以将运算符设为friend,在这种情况下,签名必须是:

template <typename U>
friend std::ostream& operator <<(std::ostream&, Matrix const&);

(同样,请注意,流首先出现,就像在您的工作代码中一样。)

你的模板operator <<看起来很好。你反对的是什么?