【问题标题】:Inherit from boost::matrix继承自 boost::matrix
【发布时间】:2022-01-13 19:09:51
【问题描述】:

我想继承boost::matrix 来丰富一些方法。我从这个开始:

#include <boost/numeric/ublas/matrix.hpp>

using namespace boost::numeric::ublas;

class MyMatrix : public matrix<double>
{
public:
    MyMatrix() : matrix<double>(0, 0) {}

    MyMatrix(int size1, int size2) : matrix<double>(size1, size2) {}

    MyMatrix(MyMatrix& mat) : matrix<double>(mat) {}

    MyMatrix(matrix<double>& mat) : matrix<double>(mat) {}

    MyMatrix& operator=(const MyMatrix& otherMatrix)
    {
        (*this) = otherMatrix;
        return *this;
    }
};

这让我可以做这样的事情:

MyMatrix matA(3, 3);
MyMatrix matB(3, 3);
MyMatrix matC(matA);

但我可能会错过一些事情,因为我无法做到:

MyMatrix matD(matA * 2);
MyMatrix matE(matA + matB);

导致:

error: conversion from 'boost::numeric::ublas::matrix_binary_traits<boost::numeric::ublas::matrix<double>, boost::numeric::ublas::matrix<double>, boost::numeric::ublas::scalar_plus<double, double> >::result_type {aka boost::numeric::ublas::matrix_binary<boost::numeric::ublas::matrix<double>, boost::numeric::ublas::matrix<double>, boost::numeric::ublas::scalar_plus<double, double> >}' to non-scalar type 'MyMatrix' requested

如何使用boost::matrix 中的方法而不在MyMatrix 中重新定义所有方法?

【问题讨论】:

  • 你确认你想继承的类有一个虚拟析构函数吗?通常最好只写一些免费的函数。
  • 这能回答你的问题吗? Thou shalt not inherit from std::vector
  • 不确定它是否达到了预期的效果,因为顶部和公认的答案说就是这样做。我觉得这是个糟糕的建议。
  • 我现在不太关心boost::numeric::ublas。你能告诉我们你想添加什么吗?您不需要任何这些函数来使示例代码正常工作。
  • 我想添加一些用户定义的方法来获取(例如,但不仅是)矩阵内值的最小值、最大值、平均值、标准差。

标签: c++ boost


【解决方案1】:

您不需要添加任何内容即可完成这项工作:

MyMatrix matA(3, 3);
MyMatrix matB(3, 3);
MyMatrix matC(matA);

MyMatrix matD(matA * 2);
MyMatrix matE(matA + matB);

您只需要将boost::numeric::ublas::matrix&lt;double&gt; 构造函数和赋值运算符带入您的派生类:

#include <boost/numeric/ublas/matrix.hpp>

class MyMatrix : public boost::numeric::ublas::matrix<double> {
public:
    using matrix<double>::matrix;    // use the constructors already defined
    using matrix<double>::operator=; // and the operator=s already defined

    // put your other additions here (except those you had in the question)
};

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多