如何将向量与来自不同类和头文件的矩阵相乘?

时间:2019-05-01 20:30:54

标签: c++11

我想通过重载*运算符将向量与Vector类中的矩阵(来自不同的类和头文件)相乘。

向量类无法识别矩阵,我什至使用Friend关键字。

这是构造函数代码:

我在单元格部分和+ =部分出现错误。

构造函数

Matrix operator*(Matrix matrix, Vector vector)
{
    double sum_of_elements = 0;
    Matrix res(matrix.getnumrows, matrix.getnumcols);
    for (int i = 0; i <matrix.getnumcols(); i++)
    {
            for (int m = 0; m < vector.Index; m++) {
                res.cell[i] += matrix.cell[i][m] * vector.cell[i];
        }
    }
    return res;
}

这是构造函数的标题: 请注意,我已经使用了friend关键字。

标题

class Vector
{
    friend std::ostream &operator<<(std::ostream &out, const Vector &vec);
    friend Matrix operator*(Matrix matrix, Vector vector);
    private:
        int Index;
        std::vector<float> cell;
    public:
        Vector();
        Vector(float a, float b, float c);

    ~Vector();

};

这是代码应在其中执行任务的源文件

来源

try {

        Matrix m1(3, 3, 1.0);
        Matrix m2(3, 4, 1.0);

        m1(1, 2) = 14.92;
        m1(0, 0) = 4.2;
        Vector v1{9.1,1.2,8.2};
        Vector v2 = m1 * v1;
        std::cout << "v2:" << v2 << std::endl;;
    }
    catch (std::exception &e) {
        std::cout << "Exception: " << e.what() << "!" << std::endl;
    }
    catch (...) {
        std::cout << "Unknown exception caught!" << std::endl;
    }

输出应如下所示:

v2:[47.62
132.644
18.5]

但是我收到6条错误消息:

Error   C2248   'Matrix::cell': cannot access private member declared in class 'Matrix' vector.cpp  25  

Error   C2440   'initializing': cannot convert from 'Matrix' to 'Vector'    source.cpp  17  

Error   C2676   binary '+=': '_Ty' does not define this operator or a conversion to a type acceptable to the predefined operator   vector.cpp       25  

Error   C3867   'Matrix::getnumrows': non-standard syntax; use '&' to create a pointer to member    vector.cpp  21

Error   C3867   'Matrix::getnumcols': non-standard syntax; use '&' to create a pointer to member    vector.cpp  21

Error (active)  E0312   no suitable user-defined conversion from "Matrix" to "Vector" exists         Source.cpp     17

0 个答案:

没有答案