Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error C2676 when compiling

Tags:

c++

I'm trying to write code in C++ (using template) to add between 2 matrices.

I have the following code in .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\study\cpp\cpp_project\cpp_project\tar5_matrix.h(36): error C2676: binary '[' : 'matrix' does not define this operator or a conversion to a type acceptable to the predefined operator

Please advise

like image 287
Lior Avramov Avatar asked May 19 '12 17:05

Lior Avramov


2 Answers

The line:

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

Should be:

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

You are trying to index the tmp variable directly, which is of type matrix<T, rows, cols>. Hence it is complaining that the matrix class doesn't provide an implementation of operator[].

like image 143
Sven Avatar answered Oct 22 '22 11:10

Sven


Since tmp is of type matrix<T, rows, cols>, the following:

tmp[i][j] = ...

uses matrix::operator[] that you haven't defined. You probably meant to say

tmp.mat[i][j] = ...
like image 21
NPE Avatar answered Oct 22 '22 13:10

NPE