Implementation of methods of interface

空扰寡人 提交于 2021-01-29 07:17:31

问题


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:

  1. 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?

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!