당신이 매우 도움이 되었기 때문에 나는 또 다른 질문을 가지고 있습니다.C++ 템플릿을 사용한 Martices 곱셈
템플릿을 사용하여 행렬 곱셈을 구현했지만 코드를 컴파일 할 수 없습니다.
여기 있습니다.
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
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;
}
, 나는 다음과 같은 오류를 얻을 컴파일하려고
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
알려 주시기 바랍니다.
죄송합니다. 잘못된 회선 번호입니다. 행 52입니다. matrix.h에 정의 된 마지막 함수의 클로저 '}' –
포함 경비원에 이중 밑줄을 사용하지 마십시오. __로 시작하는 이름은 구현을 위해 예약되어 있습니다 (예 : 컴파일러, 표준 라이브러리 및 OS)를 사용할 수 있습니다. __과 함께 이름을 사용하면 시스템 헤더의 이름과 충돌 할 위험이 있습니다. 대신'MATRIX_H' 또는'SOME_PREFIX_MATRIX_H'라고 부르십시오. –