问题
I want to implement a representation of matrices. for that I have two types of matrices - regular and sparse, which differ in their implementation - one holds a vector, and the second a map of indices and value, both inherit from Matrix
class.
For that, I'm using the strategy pattern, where I create the base abstract class Matrix
, two classes that inherit from Matrix
- RegMatrix
and SparseMatrix
, and MyMatrix
that holds a pointer to a Matrix
.
I want to implement the +
operator, which operates on Matrix
and receives another Matrix
. but when I implement the +
operator, I might receive as parameter sparse/regular matrix.
so I have 2 questions:
The only hint I have is to create an iterator of type "matrix", and implement the iterator for each type of matrix (regular and sparse). how can I do such a thing?
Let's say I implemented an iterator for both types of "matrix". how can I use the different iterators, in case I have to add two different types of matrices? do I have to implement all 4 different cases?
The operator+ looks like:
Matrix& operator+(const Matrix& other)
{
.....
}
回答1:
Prefer not to implement the functionality in the base class.
Implement the functionality in each of the child classes. This will allow for use of optimal algorithms.
Or you could declare getters and setters as abstract in the Base class and use them in your base class implementation:
struct Matrix_Base
{
virtual int get_value(unsigned int row, unsigned int column) = 0;
virtual void set_value(int value, unsigned int row, unsigned int column) = 0;
Matrix_Base operator+(const Matrix_Base& other)
{
// perform addition
int sum = get_value(row, column) + other.get_value(column, row);
set_value(sum, row, column);
//...
}
};
Remember, when passing a Matrix, the receiving function can only use common functions (interface) of the Matrix. For specifics, functions will have to use specialized (descendants) in the parameter lists.
回答2:
You may implement + operator only for RegMatrix and 2 conversion operators: 1. From RegMatrix to SparseMatrix 2. From SparseMatrix to RegMatrix
What are performance requirements?
来源:https://stackoverflow.com/questions/25593690/implementation-of-methods-of-interface