随毅 2017-06-07 15:28 采纳率: 0%
浏览 1443

求解C++析构函数释放内存错误原因,头疼。

拜托看一下我这个矩阵类实现里的析构函数哪里错了,编译没问题,运行出错。
删掉析构函数就可以运行了,为什么呢?

  • #include
  • using namespace std;
  • class CMatrix
  • {
  • public:
  • CMatrix(int, int); //构造函数
  • void output(); //输出矩阵各元素
  • CMatrix operator +(CMatrix &M2); //重载矩阵加运算
  • CMatrix operator -(CMatrix &M2); //重载矩阵减运算
  • friend istream & operator>>(istream &, CMatrix &);
  • friend ostream & operator<<(ostream &, CMatrix &);
  • ~CMatrix()
  • {
  • delete[] m_pData;
  • }
  • private:
  • int m_row; //矩阵行数
  • int m_col; //矩阵列数
  • double *m_pData; //使用指针指向矩阵各元素
  • };
  • //构造函数
  • CMatrix::CMatrix(int r, int c)
  • {
  • m_row = r;
  • m_col = c;
  • m_pData = new double[r*c];
  • for (int i = 0; i<m_row*m_col; i++)
  • m_pData[i] = 0;
  • }
  • //矩阵输出函数
  • void CMatrix::output()
  • {
  • int j = 0;
  • for (int i = 0; i<m_row*m_col; i++)
  • {
  • cout << m_pData[i] << " ";
  • if ((i + 1) % m_col == 0)
  • cout << endl;
  • }
  • }
  • //重载矩阵相加运算
  • CMatrix CMatrix::operator +(CMatrix &M2)
  • {
  • CMatrix M(m_row,m_col);
  • for (int i = 0; i<m_row*m_col; i++)
  • M.m_pData[i] = m_pData[i] + M2.m_pData[i];
  • return M;
  • }
  • //重载矩阵相减运算
  • CMatrix CMatrix::operator -(CMatrix &M2)
  • {
  • CMatrix M(this->m_row,this->m_col);
  • for (int i = 0; i<m_row*m_col; i++)
  • M.m_pData[i] = m_pData[i] - M2.m_pData[i];
  • return M;
  • }
  • istream & operator>>(istream &input, CMatrix &c)
  • {
  • for (int i = 0; i < c.m_row*c.m_col; i++)
  • input >> c.m_pData[i];
  • return input;
  • }
  • ostream & operator<<(ostream &output, CMatrix &c)
  • {
  • for (int i = 0; i < c.m_row*c.m_col; i++)
  • {
  • output << c.m_pData[i];
  • if ((i + 1) % c.m_col == 0)
  • output << endl;
  • }
  • return output;
  • }
  • int main()
  • {
  • CMatrix M1(2, 2), M2(2, 2), M3(2, 2);
  • cin >> M1;
  • cout << M1;
  • cin >> M2;
  • cout << M2;
  • M3 = M1 + M2;
  • cout << M3;
  • M3 = M1 - M2;
  • cout << M3;
  • return 0;
  • }
  • 写回答

4条回答 默认 最新

  • devmiao 2017-06-07 15:54
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?