operator =模板类中的重载

时间:2016-01-16 07:45:34

标签: c++ templates matrix operator-overloading

我正在处理矩阵模板类,现在我应该编写“=”运算符重载。 我想要做的是删除出现在'='左侧的矩阵,并返回一个等于'='右侧出现的矩阵的矩阵。

因为我无法用析构函数删除“this”,所以我在函数中“手动”删除它。但是现在我应该制作一个新的矩阵,因此我会创建一个新的(“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);
}

THX !!

2 个答案:

答案 0 :(得分:2)

使用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的引用。

答案 1 :(得分:0)

您需要为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;
}

我建议使用the answer by @Cheersandhth中提供的建议。

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

相关问题