对于不使用输出流的模板矩阵重载“+”

时间:2015-09-10 06:04:16

标签: c++ templates operator-overloading

我正在尝试重载+将两个矩阵一起添加,然后立即输出。 E.g:

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>]'|

我已经超载&lt;&lt;但我不确定如何让它一起工作。这是我到目前为止所做的:(&lt;&lt;&lt;单个矩阵可以正常工作)

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

1 个答案:

答案 0 :(得分:5)

根据为a + b声明的返回类型,matrix<T>::operator+表达式产生一个prvalue:

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

反过来,operator<<需要一个可修改的左值:

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

由于operator<<不应修改其参数,因此您可以安全地将其转换为const左值参考(如果NumRows()NumCols()为{{} {1}}合格的成员函数):

const

旁注:friend ostream& operator<< (ostream& o, const matrix<Comparable> & rhs); ~~~~^ 也应将其操作数作为operator+引用,并且本身应该const限定(如果它作为成员函数保留):

const