【发布时间】: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。你能告诉我们你想添加什么吗?您不需要任何这些函数来使示例代码正常工作。 -
我想添加一些用户定义的方法来获取(例如,但不仅是)矩阵内值的最小值、最大值、平均值、标准差。