运算符 = 模板类中的重载

operator = overload in template class

本文关键字:重载 运算符      更新时间:2023-10-16

我正在处理矩阵模板类,现在我应该编写"="运算符重载。我试图做的是删除出现在"="左侧的矩阵,并返回等于出现在"="右侧的矩阵的新矩阵。

因为我不能用析构函数删除"this",所以我在函数中"手动"删除它。 但是现在我应该创建一个新矩阵,因此我创建一个新矩阵("temp")并返回它。关键是"temp"实际上是返回的,但它没有设置在"="左侧出现的矩阵中。

代码:

Matrix<int> m (3, 4);
    Matrix<int> m2(2, 5);
    m2 = m;

这是主要部分。

该函数:

template<class T>
Matrix<T> & Matrix<T>::operator=(Matrix<T>& mat)
{
    if (this==&mat)
    {
        return *this;
    }
    for (int i = 0; i < this->rows; i++)
    {
        delete[] this->mat[i];
    }
    delete[] this->mat;
    Matrix<T> * temp = new Matrix<T>(mat.rows, mat.cols);
    for (int i = 0; i < temp->rows; i++)
        for (int j = 0; j < temp->cols; j++)
        {
            temp->mat[i][j] = mat.mat[i][j];
        }
    return *temp;
}

template<class T>
Matrix<T>::Matrix(int row, int col)
{
    rows = row;
    cols = col;
    mat = new T*[rows];
    for (int i = 0; i < rows; i++)
    {
        mat[i] = new T[cols];
    }
    rester(*this);
}

感谢!!

使用 std::vector 作为存储(而不是 manal newdelete ),并且只接受编译器生成的复制赋值运算符。就是这么简单。


如果你绝对想自己实现复制赋值,为了学习,那么只需在复制构造方面表达复制赋值。

为此,首先定义一个noexcept交换操作:

// In class definition:
friend
void swap( Matrix& a, Matrix& b )
    noexcept
{
    using std::swap;
    // swap all data members here
}

那么复制赋值运算符可以简单地表示为

// In class definition
auto operator=( Matrix other )
    -> Matrix&
{
    swap( *this, other );
    return *this;
}

它很受欢迎,一个成语,因为它非常简单但异常安全。


您可能

只想使用 void 作为返回类型,而不是返回引用,这会增加冗长程度和一些可能的边际效率低下而没有收益。但是,可能出于历史原因,标准库中的容器要求复制赋值运算符返回对 self 的引用。

您需要为this分配内存,而不是创建temp

template<class T>
Matrix<T> & Matrix<T>::operator=(Matrix<T>& rhs)
{
    if (this==&rhs)
    {
        return *this;
    }
    // Delete current memory
    for (int i = 0; i < this->rows; i++)
    {
        delete[] this->mat[i];
    }
    delete[] this->mat;
    this->rows = rhs.rows;
    this->cols = rhs.cols;
    // Allocate new memory
    // Assign values to newly allocated memory.
    this->mat = new int*[rhs.rows];
    for (int = 0; i < rhs.rows; ++i )
    {
       this->mat[i] = new int[rhs.cols];
       for (int j = 0; j < rhs.cols; j++)
       {
           this->mat[i][j] = rhs.mat[i][j];
       }
    }
    // Return *this.
    return *this;
}

我建议使用@Cheersandhth回答中给出的建议。

还要使用参数的不同名称。不要与成员变量mat和参数混淆 mat