简体   繁体   中英

Parent Class member function using instances of child class c++

I have a coursework that involves implementing two classes, one to store Matrix objects and a child of this for SquareMatrix objects. We have to implement member functions to be able to solve an equation of the form Ax = b, with A being the matrix, x being the vector we want to find and b being a known vector.

I've implemented this in the case of a SquareMatrix since it is not too hard to do with Gaussian elimination. The method that the coursework says we should use to solve the case with a non-square matrix is to solve A'Ax = A'b with ' meaning transpose. A'A is now a square matrix so this can be solved using Gaussian elimination also.

What I wanted to know was whether it is a valid thing to do to create a SquareMatrix object in the Matrix solve function and then use the SquareMatrix member solve to solve the system. So for instance if in SquareMatrix I have

Matrix SquareMatrix::solve(Matrix& b){
    //stuff that solves (*this) * x = b for x and returns x
}

Could I then in Matrix.cpp have

Matrix Matrix::solve(Matrix& b){
    //make the matrix into a square
    SquareMatrix AtransposeA = (this->transpose())*(*this);

    //update rhs of equation accordingly 
    Matrix Atransposeb = (this->transpose()) * b;

    //Call SquareMatrix solve to solve the problem.
    Matrix x = AtransposeA.solve(Atransposeb);
    return x;
}

So I'm making the matrix square by multiplying by its transpose and then calling the SquareMatrix solve function. I'm relatively new to C++ and haven't 100% gotten my head around inheritance so I'm not sure if this a valid, or sensible thing to do.

I'm not sure if this a valid, or sensible thing to do.

It is valid to use a derived class, to implement a function of parent class in some cases.

Whether it makes sense for SquareMatrix to be derived from Matrix is another consideration. To know the answer to that question, you'll need to consider your design, and outline all class invariants and member function pre- and post-conditions of Matrix and then consider whether SquareMatrix can satisfy them all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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