オブジェクトの割り当てに使用されたメモリを解放できますか? もしそうなら、どうすればいいですか?
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
}
それらは同じ出力を持っているので、動的メモリ割り当てを使用する利点は何ですか?