2010-12-08 30 views
1

Je construis une classe matricielle pour renforcer mes connaissances en C++. Mon opérateur surchargé == ne cesse cependant de renvoyer une erreur de "rejets qualificatifs", ce que je comprends être une violation des règles const de façon ou d'autre, mais je ne peux pas comprendre comment.Règles const C++?

template <class T, unsigned int rows, unsigned int cols> 
bool Matrix<T,rows,cols>::operator==(const Matrix<T,rows,cols>& second_matrix) const{ 
    if (_rows != second_matrix.getNumRows() || _cols != second_matrix.getNumCols()) 
     return false; 
    else{ 
     unsigned int i,j; 
     for (i = 0; i < rows; i++){ 
       for (j = 0; j < cols; j++){ 
       if (data[i][j] != second_matrix(i,j)) 
        return false; 
      } 
     } 
    } 

    return true; 
} 

L'erreur est renvoyé sur le 'if (data [i] [j]! = Second_matrix (i, j))' line. Donc, juste pour être complet, voici mon opérateur =:

template <class T, unsigned int rows, unsigned int cols> 
bool Matrix<T,rows,cols>::operator!=(const Matrix<T,rows,cols>& second_matrix) const{ 
    return !(*this == second_matrix); 
} 

En outre, l'opérateur():

template <class T, unsigned int rows, unsigned int cols> 
T & Matrix<T,rows,cols>::operator()(int row, int col){ 
    return data[row][col]; 
} 

Répondre

3

C'est votre() op. Ce n'est pas const. Vous ne pouvez pas appeler une fonction non-const sur un objet const. Faire une version const de() qui retourne par const & ou par valeur.

+0

Conseil @JakeVA: prototype 'const T & operator() (ligne int , int col) const; La fin de 'const' signifie que' * this' est const. – ephemient

+0

c'était tout, merci – jakev

1
template <class T, unsigned int rows, unsigned int cols> 
T & Matrix<T,rows,cols>::operator()(int row, int col){ 
    return data[row][col]; 
} 

Est non-const. Cela est correct en soi, mais pour un accès en lecture seule, vous devez surcharger cette fonction membre. Le compilateur sélectionnera alors automatiquement la surcharge const:

template <class T, unsigned int rows, unsigned int cols> 
T & Matrix<T,rows,cols>::operator()(int row, int col){ 
    return data[row][col]; 
} 
template <class T, unsigned int rows, unsigned int cols> 
const T & Matrix<T,rows,cols>::operator()(int row, int col) const{ 
    return data[row][col]; 
} 

(Vous devrez également déclarer la deuxième version dans le corps de la classe.)