mercredi 1 mai 2019

How to multiply vector with a matrix from a different class and header file?

I want to multiply a vector with a matrix (from a different class and header file) in a Vector Class by overloading the * operator.

The vector class won't recognize the Matrix and I even used the Friend keyword.

this is the constructor code:

I get an error in the cell part and += part.

Constructor

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;
}

This is the header for the constructor: Notice that I've used the friend keyword.

Header

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();

};

This is the source file where the code should perform its task

Source

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;
    }

The output should look like this:

v2:[47.62
132.644
18.5]

But I get 6 error messages:

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

Aucun commentaire:

Enregistrer un commentaire