我可以释放用于分配对象的内存吗?如果是这样,我该怎么做?
class CRectangle {
int width, height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {
return (width * height);
}
};
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
CRectangle::~CRectangle () {
// Do something here
}
如果我使用动态内存分配,它将是:
class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {
return (*width * *height);
}
};
CRectangle::CRectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}
CRectangle::~CRectangle () {
delete width
delete height
}
它们确实有相同的输出,那么使用动态内存分配有什么好处呢?