これは、cpp コードを計算する単純な四角形の領域です。これについていくつか質問があります。
#include <iostream>
#include <conio.h>
using namespace std;
class CRectangle
{
int *width, *heigth;
public:
CRectangle(int, int);
~CRectangle();
int area() { return (*width * *heigth);}
};
CRectangle :: CRectangle(int a, int b)
{
width = new int;
heigth = new int;
*width = a;
*heigth = b;
}
CRectangle :: ~CRectangle()
{
delete width;
delete heigth;
}
void main()
{
CRectangle rect1(3,4), rect2(5,6);
cout << "rect1 area = " << rect1.area() << "\n";
cout << "rect2 area = " << rect2.area();
getch();
}
- なぜそのようなオブジェクト指向コードでポインタを使用するのですか?つまり、利点は何ですか?
- このコードでは、作成したオブジェクト
rect1(3,4)
を作成した後、これrect2(5,6)
を行うと、論理的に (私が思うに) 幅と高さが指しているメモリセクションで 3 と 4 の代わりに 5 と 6 が置き換えられるため、3 と 4 はもう使用できません。しかし、彼らはです。
正確に何が起こるか説明してください。