gpt4 book ai didi

c++ - 为不适用于输出流的模板矩阵重载 "+"

转载 作者:行者123 更新时间:2023-11-30 01:13:18 35 4
gpt4 key购买 nike

我正在尝试重载 + 以将两个矩阵相加,然后立即输出。例如:

matrix<int> a, b;
...
cout << a + b << endl; //doesn't work
matrix<int> c = a + b; //works
cout << a << endl; //works

error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'|
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\ostream|602|error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = matrix<int>]'|

我已经重载了 << 但我不确定如何让它协同工作。到目前为止,这是我所拥有的:(<< 适用于单个矩阵)

template <typename Comparable>
class matrix
{
private:
size_t num_cols_;
size_t num_rows_;
Comparable **array_;

public:
friend ostream& operator<< (ostream& o, matrix<Comparable> & rhs){
size_t c = rhs.NumRows();
size_t d = rhs.NumCols();
for (int i = 0; i < c; i++){
for (int j = 0; j < d; j++){
o << rhs.array_[i][j] << " ";
}
o << endl;
}
return o;
}


matrix<Comparable> operator+ (matrix<Comparable> & rhs){
matrix<Comparable> temp(num_rows_,num_cols_);
for (int i = 0; i < num_rows_; i++){
for (int j = 0; j < num_cols_; j++){
temp.array_[i][j] = array_[i][j] + rhs.array_[i][j];
}
}
return temp;
}
}

最佳答案

a + b表达式根据为 matrix<T>::operator+ 声明的返回类型产生纯右值:

matrix<Comparable> operator+ (matrix<Comparable> & rhs);
~~~~~~~~~~~~~~~~~^

反过来,operator<<期望一个可修改的左值:

friend ostream& operator<< (ostream& o, matrix<Comparable> & rhs);
~~~~~~~~~~~~~~~~~~~^

operator<<不应该修改它的参数,你可以安全地将它变成一个 const左值引用(如果 NumRows()NumCols()const 合格的成员函数,这应该可以工作):

friend ostream& operator<< (ostream& o, const matrix<Comparable> & rhs);
~~~~^

旁注:operator+还应将其操作数视为 const引用资料,本身应该是const合格(如果它保留为成员函数):

matrix<Comparable> operator+ (const matrix<Comparable> & rhs) const;
~~~~^ ~~~~^

关于c++ - 为不适用于输出流的模板矩阵重载 "+",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32494278/

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