使用c ++模板进行Martices乘法运算

Lio*_*mov 0 c++

既然你很有帮助,我还有另外一个问题.

我已经使用模板实现了矩阵乘法,但我无法编译我的代码.

这里是.

matrix.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
Run Code Online (Sandbox Code Playgroud)

matrix.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;

}
Run Code Online (Sandbox Code Playgroud)

在尝试编译时,我收到以下错误,

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
Run Code Online (Sandbox Code Playgroud)

请指教.

Oli*_*rth 5

您还没有operator*在类体中定义.