C++析构函数

来源:百度知道 编辑:UC知道 时间:2024/06/09 03:52:39
程序如下,使用VC6.0
#include <iostream.h>
class matrix
{
short rows, cols;
double * elems;
public:
matrix(short rows, short cols);
// ~matrix();
double operator () (short row, short col);
void setelem(short row, short col, double val);
friend matrix operator + (matrix p, matrix q);
friend matrix operator - (matrix p, matrix q);
friend matrix operator * (matrix p, matrix q);
void print();
};

matrix::matrix(short rows, short cols)
{
this->rows = rows;
this->cols = cols;
elems = new double[rows * cols];
}

//matrix::~matrix()
//{
// delete []elems;
//}

double matrix::operator () (short row, short col)
{
return (row >= 1 && row <= rows && col >= 1 && col <= cols) ?
elems[(row - 1) * cols + (col - 1)] : 0.0;
}

void matrix::setelem(short row, short col, double val)

friend matrix operator + (matrix &p, matrix &q);
参数用&类型,否则传递时只会位拷贝,double * elems被多次delete;

你把子函数中的临时变量m作为返回值, 而这个值在子函数退出时会被释放而调用析构函数,这时你得到的返回值就是一个无意义的了