拜托看一下我这个矩阵类实现里的析构函数哪里错了,编译没问题,运行出错。
删掉析构函数就可以运行了,为什么呢?
- #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;
- }
http://bbs.csdn.net/topics/370209063
具体报的什么错误呢
~CMatrix()
{
delete[] m_pData; //这里可以为空,不能释放,因为没使用一次就释放了,下次在使用时指针为空。。
}
如果真想释放内存,建议写一个函数释放,在变量彻底不使用时释放!!!
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(CMatrix& a)
{
this->m_row = a.m_row;
this->m_col = a.m_col;
this->m_pData = new double[a.m_col * a.m_row];
memcpy(this->m_pData, a.m_pData, a.m_col * a.m_row);
}
加一个引用就可以了,或者加一个拷贝构造函数就可以了