运算符 = 模板类中的重载
operator = overload in template class
我正在处理矩阵模板类,现在我应该编写"="运算符重载。我试图做的是删除出现在"="左侧的矩阵,并返回等于出现在"="右侧的矩阵的新矩阵。
因为我不能用析构函数删除"this",所以我在函数中"手动"删除它。 但是现在我应该创建一个新矩阵,因此我创建一个新矩阵("temp")并返回它。关键是"temp"实际上是返回的,但它没有设置在"="左侧出现的矩阵中。
代码:
Matrix<int> m (3, 4);
Matrix<int> m2(2, 5);
m2 = m;
这是主要部分。
该函数:
template<class T>
Matrix<T> & Matrix<T>::operator=(Matrix<T>& mat)
{
if (this==&mat)
{
return *this;
}
for (int i = 0; i < this->rows; i++)
{
delete[] this->mat[i];
}
delete[] this->mat;
Matrix<T> * temp = new Matrix<T>(mat.rows, mat.cols);
for (int i = 0; i < temp->rows; i++)
for (int j = 0; j < temp->cols; j++)
{
temp->mat[i][j] = mat.mat[i][j];
}
return *temp;
}
template<class T>
Matrix<T>::Matrix(int row, int col)
{
rows = row;
cols = col;
mat = new T*[rows];
for (int i = 0; i < rows; i++)
{
mat[i] = new T[cols];
}
rester(*this);
}
感谢!!
使用 std::vector
作为存储(而不是 manal new
和 delete
),并且只接受编译器生成的复制赋值运算符。就是这么简单。
如果你绝对想自己实现复制赋值,为了学习,那么只需在复制构造方面表达复制赋值。
为此,首先定义一个noexcept
交换操作:
// In class definition:
friend
void swap( Matrix& a, Matrix& b )
noexcept
{
using std::swap;
// swap all data members here
}
那么复制赋值运算符可以简单地表示为
// In class definition
auto operator=( Matrix other )
-> Matrix&
{
swap( *this, other );
return *this;
}
它很受欢迎,一个成语,因为它非常简单但异常安全。
您可能
只想使用 void
作为返回类型,而不是返回引用,这会增加冗长程度和一些可能的边际效率低下而没有收益。但是,可能出于历史原因,标准库中的容器要求复制赋值运算符返回对 self 的引用。
您需要为this
分配内存,而不是创建temp
。
template<class T>
Matrix<T> & Matrix<T>::operator=(Matrix<T>& rhs)
{
if (this==&rhs)
{
return *this;
}
// Delete current memory
for (int i = 0; i < this->rows; i++)
{
delete[] this->mat[i];
}
delete[] this->mat;
this->rows = rhs.rows;
this->cols = rhs.cols;
// Allocate new memory
// Assign values to newly allocated memory.
this->mat = new int*[rhs.rows];
for (int = 0; i < rhs.rows; ++i )
{
this->mat[i] = new int[rhs.cols];
for (int j = 0; j < rhs.cols; j++)
{
this->mat[i][j] = rhs.mat[i][j];
}
}
// Return *this.
return *this;
}
我建议使用@Cheersandhth回答中给出的建议。
还要使用参数的不同名称。不要与成员变量mat
和参数混淆 mat
。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用