gpt4 book ai didi

c++ - 如何改进矩阵的 "="运算符重载?

转载 作者:行者123 更新时间:2023-11-27 22:40:38 24 4
gpt4 key购买 nike

我已经为带有二维数组的类重载了赋值运算符,但为了进行内存管理和正确调整大小,我必须先删除以前的矩阵,然后构造一个新矩阵,然后才能开始赋值。

Matrix& Matrix::operator = (const Matrix& m1){
for (int i = 0; i < m_rows; ++i)
delete[] m_matrix[i];
delete[] m_matrix;

m_matrix = new double*[m1.rows()];
for (int i = 0; i < m1.rows(); ++i)
m_matrix[i] = new double[m1.cols()]();

for (int k = 0; k < m1.rows(); ++k)
for (int j = 0; j < m1.cols(); ++j)
m_matrix[k][j] = m1.m_matrix[k][j];

m_rows = m1.rows();
m_cols = m1.cols();

return *this;
}

实际上,这部分是我类的析构函数:

for (int i = 0; i < m_rows; ++i)
delete[] m_matrix[i];
delete[] m_matrix;

这部分类似于构造函数:

m_matrix = new double*[m1.rows()];
for (int i = 0; i < m_rows; ++i)
m_matrix[i] = new double[m1.cols()]();

让我烦恼的是,我必须在赋值函数(以及其他一些函数!)中复制构造函数和析构函数的代码,才能使其正常工作。有没有更好的写法?

最佳答案

理想的改进是Matrix& Matrix::operator=(const Matrix&) = default;

如果您切换到使用 std::vector 进行矩阵存储,您根本不需要实现复制/移动构造函数/赋值和析构函数。

如果您正在做的是编程练习,请创建您自己的动态数组并将其用于矩阵的实现。

我不能推荐足够的观看 Better Code: Runtime Polymorphism by Sean Parent ,他有效地演示了为什么您应该努力编写不需要复制/移动构造函数/赋值和析构函数的非默认实现的类。

例子:

template<class T>
class Matrix
{
std::vector<T> storage_;
unsigned cols_ = 0;

public:
Matrix(unsigned rows, unsigned cols)
: storage_(rows * cols)
, cols_(cols)
{}

// Because of the user-defined constructor above
// the default constructor must be provided.
// The default implementation is sufficient.
Matrix() = default;

unsigned columns() const { return cols_; }
unsigned rows() const { return storage_.size() / cols_; }

// Using operator() for indexing because [] can only take one argument.
T& operator()(unsigned row, unsigned col) { return storage_[row * cols_ + col]; }
T const& operator()(unsigned row, unsigned col) const { return storage_[row * cols_ + col]; }

// Canonical swap member function.
void swap(Matrix& b) {
using std::swap;
swap(storage_, b.storage_);
swap(cols_, b.cols_);
}

// Canonical swap function. Friend name injection.
friend void swap(Matrix& a, Matrix& b) { a.swap(b); }

// This is what the compiler does for you,
// not necessary to declare these at all.
Matrix(Matrix const&) = default;
Matrix(Matrix&&) = default;
Matrix& operator=(Matrix const&) = default;
Matrix& operator=(Matrix&&) = default;
~Matrix() = default;
};

关于c++ - 如何改进矩阵的 "="运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49301272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com