编译时出错C2676

Lio*_*mov 3 c++

我正在尝试用C++编写代码(使用模板)来添加2个矩阵.

我在.h文件中有以下代码.

#ifndef __MATRIX_H__
#define __MATRIX_H__

//***************************
//         matrix
//***************************

template <class T, int rows, int cols> class matrix {
public:
    T mat[rows][cols];
    matrix();
    matrix(T _mat[rows][cols]);
    matrix operator+(const matrix& b);
};

template <class T, int rows, int cols> matrix <T,rows,cols> :: matrix (T _mat[rows][cols]){
    for (int i=0; i<rows; i++){
        for (int j=0; j<cols; j++){
            mat[i][j] = _mat[i][j];
        }
    }
}

template <class T, int rows, int cols> matrix <T,rows,cols> :: matrix (){
    for (int i=0; i<rows; i++){
        for (int j=0; j<cols; j++){
            mat[i][j] = 0;
        }
    }
}

template <class T, int rows, int cols> matrix <T,rows,cols> matrix <T,rows,cols>::operator+(const matrix<T, rows, cols>& b){
    matrix<T, rows, cols> tmp;
    for (int i=0; i<rows; i++){
        for (int j=0; j<cols; j++){
            tmp[i][j] = this->mat[i][j] + b.mat[i][j];
        }
    }
    return tmp;
}



#endif
Run Code Online (Sandbox Code Playgroud)

我的.cpp:

#include "tar5_matrix.h"
int main(){

    int mat1[2][2] = {1,2,3,4};
    int mat2[2][2] = {5,6,7,8};
    matrix<int, 2, 2> C;
    matrix<int, 2, 2> A = mat1;
    matrix<int, 2, 2> B = mat2;
    C = A+B;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译时,我收到以下错误:

1> c:\ users\karin\desktop\lior\study\cpp\cpp_project\cpp_project\tar5_matrix.h(36):错误C2676:二进制'[':'矩阵'没有定义此运算符或转换为类型预定义运算符可接受

请指教

Sve*_*ven 5

这条线:

tmp[i][j] = this->mat[i][j] + b.mat[i][j]; 
Run Code Online (Sandbox Code Playgroud)

应该:

tmp.mat[i][j] = this->mat[i][j] + b.mat[i][j]; 
Run Code Online (Sandbox Code Playgroud)

您正在尝试tmp直接索引变量,这是类型matrix<T, rows, cols>.因此,它抱怨该matrix课程没有提供实施operator[].