【问题标题】:error C2676 when compiling编译时出现错误 C2676
【发布时间】:2012-05-19 17:02:37
【问题描述】:

我正在尝试用 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

我的 .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;
}

编译时出现如下错误:

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

请指教

【问题讨论】:

  • 对于未来,我建议为您的问题使用更具描述性的标题,而不仅仅是错误编号。大多数人不知道 VC 错误编号,因此无法一眼看出他们是否能够回答您的问题。
  • 既然你这么有帮助,我还有一个问题。

标签: c++


【解决方案1】:

行:

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

应该是:

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

您正在尝试直接索引tmp 变量,它的类型为matrix&lt;T, rows, cols&gt;。因此它抱怨matrix 类没有提供operator[] 的实现。

【讨论】:

    【解决方案2】:

    由于tmp 的类型为matrix&lt;T, rows, cols&gt;,因此如下:

    tmp[i][j] = ...
    

    使用您尚未定义的matrix::operator[]。你可能是想说

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

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 1970-01-01
      • 2023-04-11
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      相关资源
      最近更新 更多