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

xyz*_*xyz 1 c++ templates operator-overloading

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

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>]'|
Run Code Online (Sandbox Code Playgroud)

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

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Pio*_*cki 5

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

matrix<Comparable> operator+ (matrix<Comparable> & rhs);
~~~~~~~~~~~~~~~~~^
Run Code Online (Sandbox Code Playgroud)

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

friend ostream& operator<< (ostream& o, matrix<Comparable> & rhs);
                                        ~~~~~~~~~~~~~~~~~~~^
Run Code Online (Sandbox Code Playgroud)

由于operator<<是不应该改变它的参数,你可以放心地把它变成一个const左值引用(这应该工作只要NumRows()NumCols()const资质的成员函数):

friend ostream& operator<< (ostream& o, const matrix<Comparable> & rhs);
                                        ~~~~^
Run Code Online (Sandbox Code Playgroud)

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

matrix<Comparable> operator+ (const matrix<Comparable> & rhs) const;
                              ~~~~^                           ~~~~^
Run Code Online (Sandbox Code Playgroud)