重载c++模板(对象)中的运算符=

Overloading operator= in c++ templates (objects)

本文关键字:运算符 对象 c++ 模板 重载      更新时间:2023-10-16

我正试图为模板对象向operator =编写一个重载,我正在创建一个模板矩阵。如果我要做m[i][j] = m2[i][j];之类的事情,我需要它,它应该适用于任何类型的参数和对象。

这是我的代码:

复制构造函数:

template<class T>
inline Matrix<T>::Matrix(const Matrix& other)
{
    this->_rows = other._rows;
    this->_cols = other._cols;
    this->_array = new T*[rows];
    for (int i = 0; i < rows; i++)
        this->_array[i] = new T[cols];
    // Copy 'temp' to 'this'
    for (int i = 0; i < this->_rows; i++)
        for (int j = 0; j < this->_cols; j++)
            this->_array[i][j] = other._array[i][j];
}

operator=过载:

template<class T>
inline T& Matrix<T>::operator=(const T &obj)
{
    // Is the same
    if (this == &obj)
    {
        return *this;
    }
    // Go to copy constructor of 'T'
    T* temp = new T(obj);
    return temp;
}

你能告诉我我需要更改或修复什么吗?

您的代码的问题是,您试图通过引用T来分配Matrix<T>,因此Matrix<T>对象不会受到分配的影响。

在设计中,您必须始终从分配运算符返回Matrix<T>&。所以代码必须是这样的。

template<class T>
inline Matrix<T>& Matrix<T>::operator=(const T &obj)
{
    // Some object member assignment
    m_SomeMember = obj;
    return *this;
}

在这种情况下,您不能检查对象的复制副本,因为T不是Matrix<T>,它只是用不同的类型成员重新分配对象。

如果仍要将Matrix<T>对象分配给另一个Matrix<T>。你的代码必须看起来像:

template<class T>
inline Matrix<T>& Matrix<T>::operator=(const Matrix<T>& obj)
{
    if (this == &obj)
    {
        return *this;
    }
    // Performing deep copying
    m_SomeMember = obj.m_SomeMember;
    return *this;
}

我还检测到您的复制构造函数存在问题。您必须使用:

template<class T>
inline Matrix<T>::Matrix(const Matrix<T>& other)
{
    /* Copy constructors body */
}

而不是

template<class T>
inline Matrix<T>::Matrix(const Matrix& other)
{
    /* Copy constructors body */
}