既然你这么有帮助,我还有一个问题。
我已经使用模板实现了矩阵乘法,但我无法编译我的代码。
这里是。
矩阵.h:
#ifndef __MATRIX_H__
#define __MATRIX_H__
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.mat[i][j] = this->mat[i][j] + b.mat[i][j];
}
}
return tmp;
}
template <class T, int rows, int cols> template <int new_cols> matrix <T,rows,new_cols> matrix <T,rows,cols>::operator*(const matrix<T, cols, new_cols>& b){
matrix<T,rows,new_cols> tmp;
int i, j, k;
T sum;
for(i=0; i<rows; i++){
for(j=0; j<new_cols; j++){
sum = 0;
for (k=0; k<cols; k++){
sum += this->mat[i][k] * b.mat[k][j];
}
tmp.mat[i][j] = sum;
}
}
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};
int res[2][2];
matrix<int, 2, 2> C;
matrix<int, 2, 2> D;
matrix<int, 2, 2> A = mat1;
matrix<int, 2, 2> B = mat2;
C = A+B;
D = A*B;
return 0;
}
尝试编译时,出现以下错误,
1> tar5_matrix.cpp
1>c:\users\karin\desktop\lior\study\cpp\cpp_project\cpp_project\tar5_matrix.h(68): error C2039: '*' : is not a member of 'matrix<T,rows,cols>'
1>c:\users\karin\desktop\lior\study\cpp\cpp_project\cpp_project\tar5_matrix.cpp(14): error C2676: binary '*' : 'matrix<T,rows,cols>' does not define this operator or a conversion to a type acceptable to the predefined operator
请指教。