动态分配矩阵的算子重载
Operator overloading with dynamic allocated matrix
我正在写一些代码来自学c++。
执行以下代码:
#include <iostream>
using namespace std;
class Matrix
{
int m, n;
public:
float** value;
Matrix(int m, int n)
{
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
this->m = m; this->n = n;
}
~Matrix()
{
for (int i = 0; i < m; ++i)
delete[] value[i];
delete[] value;
}
Matrix(const Matrix& A)
{
m = A.getLength();
n = A.getWidth();
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
value[i][j] = A.value[i][j];
}
int getLength(void) const
{
return m;
}
int getWidth(void) const
{
return n;
}
void print() const
{
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
cout << value[i][j] << "t";
cout << endl;
}
}
Matrix operator + (const Matrix& B)
{
if (m != B.getLength() || n != B.getWidth())
return Matrix(0, 0);
Matrix C = Matrix(m, n);
cout << value << endl;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
C.value[i][j] = value[i][j] + B.value[i][j];
return C;
}
void operator = (const Matrix& A)
{
m = A.getLength();
n = A.getWidth();
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
value[i][j] = A.value[i][j];
}
};
int main()
{
Matrix A = Matrix(3, 3);
A.value[0][0] = 1; A.value[0][1] = 2; A.value[0][2] = 3;
A.value[1][0] = 4; A.value[1][1] = 5; A.value[1][2] = 6;
A.value[2][0] = 7; A.value[2][1] = 8; A.value[2][2] = 9;
Matrix B = Matrix (3, 3);
B.value[0][0] = 1; B.value[0][1] = 2; B.value[0][2] = 3;
B.value[1][0] = 4; B.value[1][1] = 5; B.value[1][2] = 6;
B.value[2][0] = 7; B.value[2][1] = 8; B.value[2][2] = 9;
Matrix C = A + B;
cout << C.value << endl;
C.print();
return 0;
}
在"矩阵C = a + B"部分生成内存泄漏?我不知道关联完成后返回的矩阵是否被销毁。如果是,有办法解决吗?
In语句
Matrix C = A + B;
没有泄漏。
虽然在你的代码中没有使用复制赋值操作符,但是你的复制赋值操作符不会释放先前分配给对象矩阵的内存。复制赋值操作符与复制构造函数的不同之处在于,对象已经创建并具有分配的矩阵。你还必须检查是否有self赋值
还应该声明为
Matrix & operator = (const Matrix& A)
对于operator +
,则应声明为
Matrix operator + (const Matrix& B) const;
或
const Matrix operator + (const Matrix& B) const;
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 访问动态分配列表中的元素
- 为什么 std::equal_to会导致动态分配?
- 调用析构函数以释放动态分配的内存
- 动态分配Q_Property变量
- 在 C++ 中搜索动态分配的数组中的出现次数
- 动态分配的聊天数组打印缺失的数据和空
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 动态分配自定义类的数组和重载运算符
- 在c++中的赋值运算符重载方法中删除旧的动态分配内存
- 复制构造函数失败..重载,动态分配
- 动态分配矩阵的算子重载
- 使用动态分配和操作符重载的矩阵和
- c++中动态分配类型的重载+操作符
- 如何为表示动态分配的 2d 数组的类重载 [][] 运算符