继承自 boost::matrix

Inherit from boost::matrix

我想继承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

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

您不需要任何添加来完成这项工作:

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

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

您只需要将 boost::numeric::ublas::matrix<double> 构造函数和赋值运算符带入派生的 class:

#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