【发布时间】: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++