Templateklasse Matrix, Overloading der Multiplikation



  • Gude! 🕶

    Ich habe eine template<typename T,int m, int n> Klasse Matrix erstellt und stehe nun vor dem Problem der Multiplikation zweier Matrizen zu einer neuen Matrix.

    Der überladene Operator "*" akzeptiert nicht auf der rechten Seite eine <int,4,3> und auf der linken Seite eine <int,3,3> Matrix.
    Ist ja irgendwo auch logisch, da der Template Klasse m=4 und n=3 übergeben wird.
    Allerdings sehe ich im Moment keine Möglichkeit das zu umgehen, zwei Template Listen werden ja nicht akzeptiert.

    Klasse Matrix:

    template<typename T, int m, int n>
    class Matrix{
    public:
    	Matrix();
    	~Matrix();
    	T values[m][n];	
    	int m1 = m;
    	int n1 = n;
    	T& operator()(int j,int k)const;
    	T& operator()(int j,int k);
    	Matrix operator+(Matrix& mat) const;
    	Matrix operator*(Matrix& mat) const;
    	T min();
    	T max();
    };
    

    Methode operator*:

    template<typename T, int m,int n>
    Matrix<T,m,n> Matrix<T,m,n>::operator *(Matrix& mat) const {
    	//Multiplikation nur moeglich wenn Spaltenzahl(n) Matrix1 = Zeilenzahl Matrix2(m1)
    	if (n != mat.m1) {
    		std::cout << "UNGUELTIGE MULTIPLIKATION!\n" << std::endl;
    	}
    	Matrix<T,m,n> result;
    	T res = 0;
    	for (int m0 = 0; m0 < m; m0++) {
    		for (int n0 = 0; n0 < mat.n1; n0++) {
    			res = 0;
    			for (int a = 0; a < m; a++) {
    				res += values[m0][a] * mat.values[a][n0];
    				result.values[m0][n0] = res;
    			}
    		}
    	}
    	return result;
    }
    

    Vielleicht kann jemand helfen. 👍
    Ich verwende MVS Community 2015


  • Mod

    FaultyBrain schrieb:

    zwei Template Listen werden ja nicht akzeptiert.

    Doch?

    template <typename T, int M, int N> class Matrix
    {
      template<int K> Matrix<T, M, K> operator*(const Matrix<T, N, K>&);
    };
    
    template<typename T, int M, int N> template<int K> Matrix<T, M, K> Matrix<T, M, N>::operator*(const Matrix<T, N, K>&) { /* ... */ }
    

    Oder direkt in der Klasse implementiert:

    template <typename T, int M, int N> class Matrix
    {
      template<int K> Matrix<T, M, K> operator*(const Matrix<T, N, K>&) { /* ... */ }
    };
    

    Aber: Der zweiseitige Operator* sollte wohl sowieso eine freie Funktion sein:

    template<typename T, int M, int N, int K> Matrix<T, M, K> operator*(const Matrix<T, M, N> &, const Matrix<T, N, K>&) { /* ... */ }
    


  • Danke, war nur ein Syntaxfehler 👍


Anmelden zum Antworten