在c ++模板(对象)中重载operator =

时间:2016-01-09 18:02:07

标签: c++ operator-overloading

我试图为模板对象写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; } 重载:

{{1}}

你能告诉我需要改变或修理的东西吗?

1 个答案:

答案 0 :(得分:0)

您的代码问题在于您尝试通过Matrix<T>的引用分配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;
}

在这种情况下,您不能检查dublicates的对象,因为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 */
}