我正在思考如何用加法(减法(和乘法运算定义一类实矩阵NxN。我正在寻找高效内存使用率。
class Matrix {
private:
std::size_t _size_n;
double **_pMatrix;
public:
Matrix(const size_t n);
~Matrix();
double &operator()(size_t, const size_t);
double operator()(size_t, const size_t) const;
size_t size_n() const { return _size_n; }
};
std::ostream &operator<<(std::ostream &, const Matrix &);
Matrix operator+(const Matrix&, const Matrix&);
Matrix operator-(const Matrix&, const Matrix&);
Matrix operator*(const Matrix&, const Matrix&);
是的,您可以有额外的过载
Matrix/*&&*/ operator+(const Matrix&, Matrix&&);
Matrix/*&&*/ operator+(Matrix&&, const Matrix&);
Matrix/*&&*/ operator+(Matrix&&, Matrix&&);
重复使用其中一个临时的内存。
它们都可以用Matrix& operator += (Matrix&, const Matrix&)
实现通过将顺序更改为+是对称的。CCD_ 2将需要专用代码。
另一种优化内存的方法是使用表达式模板,而不是直接计算结果。
然而,它在寿命问题上也有缺点(尤其是auto
(。