c ++全局运算符与模板类不兼容

2 c++ generics templates function

好吧,我在stackoverflow上发现了一些类似的帖子,但我找不到任何与我的确切情况相关的内容,而且我对给出的一些答案感到困惑.好的,所以这是我的问题:

我有一个模板矩阵类如下:

    template <typename T, size_t ROWS, size_t COLS>
    class Matrix
    {
 public:

  template<typename, size_t, size_t>
  friend class Matrix;

  Matrix( T init = T() )
   : _matrix(ROWS, vector<T>(COLS, init))
  {
   /*for( int i = 0; i < ROWS; i++ )
   {
    _matrix[i] = new vector<T>( COLS, init );
   }*/
  }

  Matrix<T, ROWS, COLS> & operator+=( const T & value )
  {
   for( vector<T>::size_type i = 0; i < this->_matrix.size(); i++ )
   {
    for( vector<T>::size_type j = 0; j < this->_matrix[i].size(); j++ )
    {
     this->_matrix[i][j] += value;
    }
   }
   return *this;
  }

 private:
  vector< vector<T> > _matrix;
    };
Run Code Online (Sandbox Code Playgroud)

我有以下全局函数模板:

    template<typename T, size_t ROWS, size_t COLS>
    Matrix<T, ROWS, COLS> operator+( const Matrix<T, ROWS, COLS> & lhs,
        const Matrix<T, ROWS, COLS> & rhs )
    {
     Matrix<T, ROWS, COLS> returnValue = lhs;
     return returnValue += lhs;
    }
Run Code Online (Sandbox Code Playgroud)

对我来说,这似乎是正确的.但是,当我尝试编译代码时,我收到以下错误(从操作符+函数抛出):

binary '+=' : no operator found which takes a right-hand operand of type 'const matrix::Matrix<T,ROWS,COLS>' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚该怎么做.任何帮助,如果非常感谢!

Tyl*_*nry 6

operator+=在这里:

Matrix<T, ROWS, COLS> & operator+=( const T & value )
Run Code Online (Sandbox Code Playgroud)

定义一种向T(a)添加(标量)的方法Matrix<T, ROWS, COLS>.

这个说法:

return returnValue += lhs;
Run Code Online (Sandbox Code Playgroud)

尝试添加Matrix<T, ROWS, COLS>(矩阵,类型lhs)到a Matrix<T, ROWS, COLS>.

所以编译器完全正确地说你还没有定义那个操作.你有operator+=一个标量添加到矩阵,但不是operator+=一个矩阵添加矩阵.