The symmetric operation is the destruction of objects. This is required as soon
as the object dynamically allocates other objects.
The special method defined to do that is called the destructor, and is called as
soon as the compiler need to deallocate an instance of the class. There is only
one destructor per class, which return no value, and has no parameter. The
name of the destructor is the class name prefixed with a ~.
We can now re-write our matrix class :
class Matrix {
int width, height;
double *data;
public:
Matrix(int w, int h) {
width = w; height = h;
data = new double[width * height];
}
~Matrix() { delete[] data; }
double getValue(int i, int j) {
if((i<0) || (i>=width) || (j<0) || (j>=height)) abort();
return data[i + width*j];
}
void setValue(int i, int j, double x) {
if((i<0) || (i>=width) || (j<0) || (j>=height)) abort();
data[i + width*j] = x;
}
};
No comments:
Post a Comment