gpt4 book ai didi

c++ - 编译时报错C2676

转载 作者:太空狗 更新时间:2023-10-29 20:29:14 26 4
gpt4 key购买 nike

我正在尝试用 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): error C2676: binary '[' : 'matrix' does not define this operator or a conversion to a type acceptable to the predefined operator

请指教

最佳答案

行:

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<T, rows, cols> .因此它提示 matrix类不提供 operator[] 的实现.

关于c++ - 编译时报错C2676,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10667207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com