繁体   English   中英

模板矩阵-矩阵乘法C ++

[英]Template Matrix-Matrix multiplication c++

我正在尝试使用模板做矩阵-矩阵乘法,并且不断出现以下错误。 (我试图乘以非平方矩阵)

错误1错误C2593:“运算符*”不明确

有人可以给我建议如何解决此问题吗?

//Matrix.h
#pragma once
#include <iostream>
#include <vector>
using namespace std;

template<class T, int m, int n>
class Matrix;

template<class T, int m, int n, int l>
Matrix<T, m, n> operator*(const Matrix<T, m, n>&, const Matrix<T, n, l>&);

template<class T, int m, int n>
class Matrix
{
vector<vector<T>> elements;
int nrow;
int ncol;

public:
    Matrix();
    ~Matrix();
    void print();
    template<int l>
    friend Matrix<T, m, l> operator*<>(const Matrix<T, m, n>&, const Matrix<T, n, l>&);

};

template<class T, int m, int n>
Matrix<T, m, n>::Matrix() : nrow(m), ncol(n)
{
    for (int i = 0; i < nrow; i++){
        vector<T> row(ncol, i);
        elements.push_back(row);
    }
}

template<class T, int m, int n>
Matrix<T, m, n>::~Matrix(){}

template<class T, int m, int n>
void Matrix<T, m, n>::print()
{
    for (int i = 0; i < nrow; i++){
        for (int j = 0; j < ncol; j++){
            cout << elements[i][j] << " ";
        }
    cout << endl;
    }
}

template<class T, int m, int n, int l> 
Matrix<T, m, l> operator*(const Matrix<T, m, n>& m1, const Matrix<T, n, l>& m2){
    int nrow = m1.nrow;
    int ncol = m2.ncol;
    Matrix<T, m, l> m3;
    for (int i = 0; i < nrow; ++i){
        for (int j = 0; j < ncol; ++j){
            m3.elements[i][j] = 0;
            for (int k = 0; k < m1.ncol; k++){
                T temp = m1.elements[i][k] * m2.elements[k][j];
                m3.elements[i][j] = temp + m3.elements[i][j];
            }
        }
    }
return m3;
}

//main.cpp
#include "Matrix.h"
using namespace std;

int main()
{
Matrix<int, 3, 2> a;
Matrix<int, 2, 1> b;
Matrix<int, 3, 1> c;
c = a*b;

c.print();
}

矩阵乘法可能会由于模板中的编码错误而出现问题。

错误在这里:

./matrix.cpp:48:28: error: function template partial specialization is not allowed
    friend Matrix<T, m, l> operator*<>(const Matrix<T, m, n>&, const Matrix<T, n, l>&);
                           ^        ~~
1 error generated.

更改为此:

friend Matrix<T, m, l> operator*(const Matrix<T, m, n>&, const Matrix<T, n, l>&);

我必须更改Richard更改的内容,但还必须更改operator*friend的声明,如下所示:

template<class T, int m, int n, int l>
Matrix<T, m, l> operator*(const Matrix<T, m, n>&, const Matrix<T, n, l>&);
          // ^ here

和:

template<class _T, int _m, int _n, int l>
friend Matrix<_T, _m, l> operator*(const Matrix<_T, _m, _n>&, const Matrix<_T, _n, l>&);

如果我没有更改这两个中的第一个,则会出现“ operator* is aambiguous”错误,因为前向声明与进一步向下的实例化不匹配。

当前正在输出:

0
1
2

这似乎不太正确,但是我还不够清醒,无法进一步调试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM