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

标签 c++ operator-overloading

我正在尝试为模板对象编写 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;
}

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

最佳答案

您的代码的问题是您试图分配 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;
}

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

关于c++ - 在 C++ 模板(对象)中重载 operator=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34697020/

相关文章:

具有私有(private)访问说明符的 C++ 派生类

c++ - 全局范围内的智能指针

c++ - 是否可以对全局运算符 `new` 和 `delete` 执行回调?

c++ - 错误 : invalid operands of types ‘int’ and ‘<unresolved overloaded function type>’ to binary ‘operator/’

c++ - 局部变量模板的实例化

c++ - 如何根据其模式从 xml 文件中检索数据

c++ - 在 3d 空间中的 QT 中围绕其 Y 轴旋转小部件

kotlin - 如何在 Kotlin 中定义自定义赋值运算符重载?

c++ - 比较具有替代顺序的自定义类型的 std::tuple(或 std::pair)。是否可以插入自定义小于/比较函数?

c++ - 我正在尝试重载运算符<<