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__
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