Compilation Error C2676

I am trying to write C ++ code (using a template) to add between two matrices.

I have the following code in a .h file.

#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

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

When compiling, I get the following error:

1> C: \ Users \ Karin \ Desktop \ Lior \ research \ CPP \ cpp_project \ cpp_project \ tar5_matrix.h (36): error C2676: binary '[': 'matrix' does not define this operator or conversion to a type acceptable for predefined operator

Please inform

+3
source share
2 answers

Line:

tmp[i][j] = this->mat[i][j] + b.mat[i][j]; 

Must be:

tmp.mat[i][j] = this->mat[i][j] + b.mat[i][j]; 

You are trying to index a variable tmpdirectly that has a type matrix<T, rows, cols>. Therefore, he complains that the class matrixdoes not provide an implementation operator[].

+5
source

tmp matrix<T, rows, cols>, :

tmp[i][j] = ...

matrix::operator[], . , ,

tmp.mat[i][j] = ...
+1

All Articles