随毅 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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)