オブジェクト属性のポインタの使い方
- #include
- using namespace std;
-
- /**
- * 1:
- */
-
- class Point {
- public:
- Point(int x, int y) {
- this->x = x;
- this->y = y;
- }
- int x;
- int y;
- };
-
- class Rectangle {
- public:
- enum pointType {
- LT, RB
- };
-
- // Rectangle
- Rectangle() {
- }
-
- // Rectangle
- ~Rectangle() {
- if (this->lt) {
- delete this->lt;
- this->lt = 0;
- }
- if (this->rb) {
- delete this->rb;
- this->rb = 0;
- }
- }
-
- void setPoint(int pt, int x, int y) {
- switch (pt) {
- case LT:
- this->deletePoint(this->lt);
- this->lt = new Point(x, y);
- break;
- case RB:
- this->deletePoint(this->rb);
- this->rb = new Point(x, y);
- break;
- }
- }
-
- int getArea() const {
- int width = 0;
- int height = 0;
- width = this->rb->x - this->lt->x;
- height = this->rb->y - this->lt->y;
- return width * height;
- }
-
- private:
- Point * lt;
- Point * rb;
-
- void deletePoint(Point * point) {
- if (point) {
- delete point;
- point = 0;
- }
- }
-
- };
-
-
- #include
- #include ../header/class.hpp
- using namespace std;
-
- int main() {
- Rectangle * theRect = new Rectangle();
- theRect->setPoint(theRect->LT, 0, 0);
- theRect->setPoint(theRect->RB, 10, 5);
- cout << theRect->getArea() << endl;
-
- theRect->setPoint(theRect->RB, 10, 10);
- cout << theRect->getArea() << endl;
-
- /*
- Rectangle theRect;
- theRect.setPoint(theRect.LT, 0, 0);
- theRect.setPoint(theRect.RB, 10, 5);
- cout << theRect.getArea() << endl;
- */
- return 0;
- }