c++ - 接口(interface)方法的实现

标签 c++ inheritance matrix iterator polymorphism

我想实现矩阵的表示。为此,我有两种类型的矩阵 - 规则矩阵和稀疏矩阵,它们的实现不同 - 一种包含一个 vector ,第二种是索引和值的映射,它们都继承自 Matrix 类。 为此,我使用了策略模式,我在其中创建了基础抽象类 Matrix,两个继承自 Matrix 的类 - RegMatrixSparseMatrixMyMatrix 包含指向 Matrix 的指针。

我想实现 + 运算符,它对 Matrix 进行运算并接收另一个 Matrix。但是当我实现 + 运算符时,我可能会收到作为参数的稀疏/规则矩阵。

所以我有两个问题:

  1. 我唯一的提示是创建一个“矩阵”类型的迭代器,并为每种类型的矩阵(规则和稀疏)实现迭代器。 我怎么能做这样的事?

  2. 假设我为两种类型的“矩阵”实现了一个迭代器。如果我必须添加两种不同类型的矩阵,我该如何使用不同的迭代器?我必须实现所有 4 种不同的情况吗?

operator+ 看起来像:

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

最佳答案

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

在每个子类中实现功能。这将允许使用最佳算法。

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

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);
    //...
  }
};

请记住,传递一个Matrix时,接收函数只能使用Matrix的公共(public)函数(接口(interface))。具体来说,函数必须在参数列表中使用专门的(后代)。

关于c++ - 接口(interface)方法的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593690/

相关文章:

c++ - 为什么重复继承/重复继承无效?

c - C 中数组下标错误的无效类型 'int[int]'?

python - 由 numpy.linalg.eig 创建的特征向量似乎不正确

c++ - 为什么指针指向指针?

c++ - 我如何证明 delete 不会释放 new [] 分配的所有内存?

c++ - 连接来自另一个在 Qt 中不起作用的类的插槽

c++ - 与 C++ 中的 virtual 关键字混淆

c++ - 如何在不创建 "friend"的情况下访问类外的私有(private)数据成员?

c++ - 调用基类构造函数与初始化子类中的成员变量

matlab - Julia 相当于 MATLAB 的 `sym` ?