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