接口方法的实现 [英] Implementation of methods of interface

查看:95
本文介绍了接口方法的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现矩阵的表示形式.为此,我有两种类型的矩阵-规则矩阵和稀疏矩阵,它们的实现方式有所不同-一种矩阵具有向量,第二种矩阵是由Matrix类继承的索引和值的映射. 为此,我使用了策略模式,在其中创建了基本抽象类Matrix,两个从Matrix-RegMatrixSparseMatrix继承的类以及MyMatrix持有指向Matrix.

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.

我想实现+运算符,该运算符在Matrix上运行并接收另一个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.

所以我有2个问题:

  1. 我唯一的提示是创建矩阵"类型的迭代器,并为每种类型的矩阵(常规和稀疏)实现该迭代器. 我该怎么做?

  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?

比方说,我为两种类型的矩阵"实现了迭代器.如果必须添加两种不同类型的矩阵,如何使用不同的迭代器?我必须实现所有4种不同的情况吗?

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?

operator +看起来像:

The operator+ looks like:

Matrix& operator+(const Matrix& other)
{
   .....
}

推荐答案

最好不要在基类中实现该功能.

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.

或者您可以在基类中将getter和setter声明为抽象,并在基类实现中使用它们:

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.

这篇关于接口方法的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆