5

2つの行列の間に追加するコードを(テンプレートを使用して)C++で記述しようとしています。

.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:バイナリ'[':'行列'はこの演算子または型への変換を定義していません事前定義されたオペレーターに受け入れ可能

お知らせ下さい

4

2 に答える 2

6

この線:

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[]ます。

于 2012-05-19T17:05:19.633 に答える
1

tmpはタイプなのでmatrix<T, rows, cols>、次のようになります。

tmp[i][j] = ...

matrix::operator[]定義していない使用。あなたはおそらく言うつもりだった

tmp.mat[i][j] = ...
于 2012-05-19T17:05:49.440 に答える