我创建了自定义类,它的行为类似于矩阵。我已经完成了一些基本操作,一切似乎都运行良好......然而,我不知道,我应该写什么给这个类的析构函数来释放所有分配的内存。你能给我建议吗?
class CMatrix {
public:
class Proxy {
friend class CMatrix;
const CMatrix* cmat;
CMatrix *matrix;
size_t n;
Proxy(const CMatrix& m, size_t i)
: cmat(&m), matrix(), n(i) {
}
Proxy(CMatrix& m, size_t i)
: cmat(&m), matrix(&m), n(i) {
}
public:
const double& operator[](size_t j) const {
return cmat->_arrayofarrays[n * cmat->y + j];
}
double& operator[](size_t j) {
if (matrix) {
return matrix->_arrayofarrays[n * cmat->y + j];
} else return cmat->_arrayofarrays[cmat->y];
}
};
const Proxy operator[](size_t i) const {
return Proxy(*this, i);
}
Proxy operator[](size_t i) {
return Proxy(*this, i);
}
CMatrix() {
_arrayofarrays = NULL;
x = 0;
y = 0;
};
// constructor
CMatrix(size_t x, size_t y) : _arrayofarrays(), x(x), y(y) {
_arrayofarrays = new double[ x * y ]();
}
// destructor
~CMatrix() {
// ?!?!???!?!?!?!!!!?!?!?
// #$#%@^$!!!!@$#%!!
}
// copy constructor
CMatrix(const CMatrix& other) : _arrayofarrays(), x(other.x), y(other.y) {
delete [] _arrayofarrays;
_arrayofarrays = new double[x * y];
if (_arrayofarrays)
std::copy(other._arrayofarrays, other._arrayofarrays + (x * y), _arrayofarrays);
}
CMatrix& operator =(const CMatrix& rval) {
delete [] _arrayofarrays;
_arrayofarrays = new double[ rval.x * rval.y];
std::copy(rval._arrayofarrays, rval._arrayofarrays + (rval.x * rval.y), _arrayofarrays);
x = rval.x;
y = rval.y;
return *this;
}
double *_arrayofarrays;
size_t x;
size_t y;
};
编辑:
实际上现在我已经意识到,它在运行这部分代码后崩溃了。在调用这段代码之前,我有一个我的类的实例,让我们调用它a,b,c
然后我想设置a = b-c
;这第一次效果很好......但是当我想重复它时,它就会崩溃
CMatrix CMatrix::operator-(const CMatrix &matrix) const {
if (this->x != matrix.x || this->y != matrix.y) {
throw CSizeException(matrix.y, matrix.x, this->y, this->x, '+');
};
CMatrix m(this->x, this->y);
CMatrix l(matrix.x, matrix.y);
l._arrayofarrays = this->_arrayofarrays;
CMatrix o(matrix.y, matrix.y);
o = matrix;
CMatrix result(this->x, this->y);
for (unsigned int i = 0; i < this->x; i++)
for (unsigned int j = 0; j < this->y; j++)
m[i][j] = l[i][j] - o[i][j];
return m;
}