未分配内存指针的大三泄漏的C++错误未分配(不重复)
我的代码运行不正确,我不知道如何修复它。这不是一个重复的问题,有人问什么是三的规则,因为这篇文章没有帮助我解决我的问题,因为在这篇文章我使用指针数组。我不知道我在三大功能中做错了什么,但有人能帮我纠正我的错误吗。编译器正在突出显示delete[]矩阵[i];在for循环中,当i=2时,在析构函数中 在我的头文件中,我有:未分配内存指针的大三泄漏的C++错误未分配(不重复),c++,rule-of-three,C++,Rule Of Three,我的代码运行不正确,我不知道如何修复它。这不是一个重复的问题,有人问什么是三的规则,因为这篇文章没有帮助我解决我的问题,因为在这篇文章我使用指针数组。我不知道我在三大功能中做错了什么,但有人能帮我纠正我的错误吗。编译器正在突出显示delete[]矩阵[i];在for循环中,当i=2时,在析构函数中 在我的头文件中,我有: #ifndef fasdf_dynn_h #define fasdf_dynn_h #include <iostream> #include <fstrea
#ifndef fasdf_dynn_h
#define fasdf_dynn_h
#include <iostream>
#include <fstream>
#include<string>
#include <cstdlib>
#include <vector>
using namespace std;
template <class T>
class MatrixdynVector{
public:
// MatrixdynVector()
{
//creates a 3 by 3 matrix with elements equal to 0
m=3;
n=3;
matrix=new int*[m];
for(int i=0;i<m;i++)
matrix[i]=new int[n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
matrix[i][j]=0;
}
// MatrixdynVector(int m,int n);
template <class H>
MatrixdynVector<H>(const MatrixdynVector<H>& c)//copy constructor
{
m=c.m;
n=c.n;
for (int i = 0; i < c.m; i++)
for (int j = 0; j < c.n; j++)
matrix[i][j] = c.matrix[i][j]; // add data to it
}
template <class H>
MatrixdynVector<H>& operator =(const MatrixdynVector<H>& c)//asignment
{
if (this == &c)
{
return *this;
}
else
{
matrix = new int*[c.m];
for (int i = 0; i < c.m; i++)
matrix[i] = new int[c.n]; // create a multi dimensional array
for (int i = 0; i < c.m; i++)
for (int j = 0; j < c.n; j++)
matrix[i][j] = c.matrix[i][j]; // add data to it
for (int i = 0; i < c.m; i++)
delete[] matrix[i]; // delete the second dimension of the matrix
delete[] matrix; // delete the first*/
return *this;
}
}
~MatrixdynVector()
{
if(matrix!=NULL)
{
for (int i = 0; i < m; i++)
delete[] matrix[i]; // delete the second dimension of the matrix
delete[] matrix; // delete the first
matrix=NULL;
}
}
private:
int m,n;
int** matrix;
};
#endif
模板不是复制构造函数
template <class H>
MatrixdynVector(const MatrixdynVector<H>&) // without <H>, which is an syntax error
另外:正确配对new和delete您在构造函数中没有新的内容。我无法编译它来验证,但我认为您应该有这样的内容:
template <class H>
MatrixdynVector(const MatrixdynVector<H>&) // without <H>, which is an syntax error
编辑:
在编辑并与问题作者交谈后。这里是一个工作版本
如果没有
定义fasdf_dynn_h
包括
包括
包括
包括
使用名称空间std;
样板
类MatrixdynVector{
私人:
int m,n;
T**矩阵;
公众:
矩阵向量;
矩阵向量m,int n;
MatrixDynVector对角线,int n,int m;
matrixdynvectorcont MatrixdynVector&c;//复制构造函数
虚拟矩阵向量;
MatrixdynVector&operator=const MatrixdynVector&c;//赋值
矩阵同步向量算子;
friend ostream&operator我的代码没有正确编译,也许你应该编辑这个问题来发布编译器错误。@drescherjm我做了,但我担心有人会认为这是一篇重复的文章,因为它与三巨头有关,但原始文章对我的问题没有帮助。无论如何,我已经更新了标题a运行时错误编译器错误。@drescherjm Ok很抱歉,我的意思是,我遇到了一个运行时错误,导致程序设置断点。请帮助我您的复制构造函数代码错误。我仍然遇到相同的运行时错误。编译器正在突出显示delete[]matrix[I];在for循环中,当i=2时,在析构函数中,你有什么运行时错误,你能用你的类给我们函数吗?阅读你的评论,我认为你的代码缺少一个默认构造函数,初始化矩阵为null,n和m为0。我将它添加到我的代码中。尽管我的默认构造函数应该创建一个元素等于零的3乘3矩阵,因此我不认为将矩阵初始化为null会对我有什么帮助。我将在我的帖子中添加我的默认构造函数,以便您可以看到我所做的