重载c++模板(对象)中的运算符=
Overloading operator= in c++ templates (objects)
我正试图为模板对象向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 */
}
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 运算符重载 += 添加新对象
- 如何用 2 个对象过度引导运算符
- C++内联运算符重载中,请参阅当前对象
- 使用运算符"="在C++中用值初始化对象
- C++运算符重载做双 * 对象
- 如何在自定义对象的<<运算符中添加自定义前缀
- 尝试重载输出运算符时,我无法遍历对象向量
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 在之后仍需要使用源对象时调用父移动分配运算符
- 错误:三元运算符无法在对象中正常工作"cout"
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 无法使用迭代器查找类对象。(二进制 '==': 'userInfo' 不定义此运算符)
- 重载加法运算符(使用函数向对象添加字符串)
- 临时对象上的运算符重载
- 如何使用运算符+重载函数正确返回对象?
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 重载运算符 [] 用于从对象数组中给出特定索引