gpt4 book ai didi

c++ - 错误 : cannot bind ‘std::ostream {aka std::basic_ostream}’ lvalue to ‘std::basic_ostream&&’

转载 作者:行者123 更新时间:2023-11-28 05:19:53 26 4
gpt4 key购买 nike

你好everonye即使我在这里找到了很多关于这个问题的答案,但一个人根本无法向我解释事情的进展如何无法解决它。

所以我的问题是我有一个名为 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;
}

有效:(谁能解释一下我在这里做错了什么

最佳答案

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

无法实现流式传输 operator <<operator >>作为 UDT 的成员函数,因为第一个参数必须始终是流。你可以让运算符(operator)成为 friend ,在这种情况下,签名需要是:

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

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

您的模板 operator <<看起来很好。你对此有何异议?

关于c++ - 错误 : cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41730474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com